是否可以使用 SVG 路径通过google_maps_flutter插件创建标记?我知道您可以.png通过以下方式使用文件:
icon: BitmapDescriptor.fromAsset("images/myFile.png")
Run Code Online (Sandbox Code Playgroud)
SVG 路径怎么样?
谢谢
red*_*uht 13
这可以使用flutter_svg包来实现。
import 'dart:ui' as ui; // imported as ui to prevent conflict between ui.Image and the Image widget
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
Future<BitmapDescriptor> _bitmapDescriptorFromSvgAsset(BuildContext context, String assetName) async {
// Read SVG file as String
String svgString = await DefaultAssetBundle.of(context).loadString(assetName);
// Create DrawableRoot from SVG String
DrawableRoot svgDrawableRoot = await svg.fromSvgString(svgString, null);
// toPicture() and toImage() don't seem to be pixel ratio aware, so we calculate the actual sizes here
MediaQueryData queryData = MediaQuery.of(context);
double devicePixelRatio = queryData.devicePixelRatio;
double width = 32 * devicePixelRatio; // where 32 is your SVG's original width
double height = 32 * devicePixelRatio; // same thing
// Convert to ui.Picture
ui.Picture picture = svgDrawableRoot.toPicture(size: Size(width, height));
// Convert to ui.Image. toImage() takes width and height as parameters
// you need to find the best size to suit your needs and take into account the
// screen DPI
ui.Image image = await picture.toImage(width, height);
ByteData bytes = await image.toByteData(format: ui.ImageByteFormat.png);
return BitmapDescriptor.fromBytes(bytes.buffer.asUint8List());
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像往常一样使用 BitmapDescriptor 创建一个标记:
BitmapDescriptor bitmapDescriptor = await _bitmapDescriptorFromSvgAsset(context, 'assets/images/someimage.svg');
Marker marker = Marker(markerId: MarkerId('someId'), icon: bitmapDescriptor, position: LatLng(someLatitude, someLongitude));
Run Code Online (Sandbox Code Playgroud)
小智 13
使用最新版本的 flutter_svg (我的例子是 2.0.1),你可以通过这种方式实现它:
class BitmapDescriptorHelper {
static Future<BitmapDescriptor> getBitmapDescriptorFromSvgAsset(
String assetName, [
Size size = const Size(48, 48),
]) async {
final pictureInfo = await vg.loadPicture(SvgAssetLoader(assetName), null);
double devicePixelRatio = ui.window.devicePixelRatio;
int width = (size.width * devicePixelRatio).toInt();
int height = (size.height * devicePixelRatio).toInt();
final scaleFactor = math.min(
width / pictureInfo.size.width,
height / pictureInfo.size.height,
);
final recorder = ui.PictureRecorder();
ui.Canvas(recorder)
..scale(scaleFactor)
..drawPicture(pictureInfo.picture);
final rasterPicture = recorder.endRecording();
final image = rasterPicture.toImageSync(width, height);
final bytes = (await image.toByteData(format: ui.ImageByteFormat.png))!;
return BitmapDescriptor.fromBytes(bytes.buffer.asUint8List());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3494 次 |
| 最近记录: |