How to change the icon size of Google Maps marker in Flutter?

前端 未结 14 620
不知归路
不知归路 2020-12-07 12:32

I am using google_maps_flutter in my flutter app to use google map I have custom marker icon and I load this with BitmapDescriptor.fromAsset(\"images/car.

相关标签:
14条回答
  • 2020-12-07 13:30

    Try BitmapDescriptor.fromAssetImage. It will ignore the image size as well.

    BitmapDescriptor.fromAssetImage(
                ImageConfiguration(size: Size(32, 32)), 'assets/car.png')
            .then((onValue) {
          setState(() {
            markerIcon = onValue;
          });
        });
    

    Also using default configuration fails.

    loadMarkerImage(BuildContext context) {
        var config = createLocalImageConfiguration(context, size: Size(30, 30));
        BitmapDescriptor.fromAssetImage(config, 'assets/car.png')
            .then((onValue) {
          setState(() {
            markerIcon = onValue;
          });
        });
      }
    
    0 讨论(0)
  • 2020-12-07 13:30

    All the answers given are perfect but I noticed that when you set the targetWidth to a specified number then you might have issues with different phones that have a different devicePixelRatio. So this is how I implemented it.

    import 'dart:ui' as ui;
    import 'dart:typed_data';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    
      Future<Uint8List> getBytesFromAsset(String path) async {
        double pixelRatio = MediaQuery.of(context).devicePixelRatio;
        ByteData data = await rootBundle.load(path);
        ui.Codec codec = await ui.instantiateImageCodec(
            data.buffer.asUint8List(),
            targetWidth: pixelRatio.round() * 30
        );
        ui.FrameInfo fi = await codec.getNextFrame();
        return (await fi.image.toByteData(format: ui.ImageByteFormat.png)).buffer.asUint8List();
      }
    
    

    and use the method like this

    final Uint8List markerIcon = await getBytesFromAsset('assets/images/bike.png');
    
    Marker(icon: BitmapDescriptor.fromBytes(markerIcon),)
    

    That gives me a dynamic size depending on the devicePixelRatio.

    This worked perfectly for me.

    0 讨论(0)
提交回复
热议问题