Cal*_*nes 1 c# google-maps google-maps-api-3 xamarin xamarin.forms
我在我的便携式项目中使用 Xamarin.Forms.GoogleMaps。它在 iOS 和 Android 上运行得很好。现在我正在研究谷歌地图的图钉/标记。我正在尝试添加不同颜色的图钉,但并非所有颜色都有效。
我现在是怎么做的:
var pin = new Xamarin.Forms.GoogleMaps.Pin();
pin.Label = ... etc etc etc
pin.Icon = BitmapDescriptorFactory.DefaultMarker(Color.Azure);
Run Code Online (Sandbox Code Playgroud)
上面的例子效果很好。但是,如果我将其更改为Color.Black,例如,它不起作用并显示默认红色的标记。而且它在不同平台上也有问题,在 iOS 中,Black 可以工作,在 Android 中不行。(没有出现错误,只是显示默认的红色而不是黑色)
所以我的问题是:
是否有可接受的颜色列表可用作标记/图钉颜色?是每种颜色都可以使用还是只是一些预定义的颜色?
另外,如何将默认图标更改为另一个图标图像?我尝试使用“FromBundle”,但它抛出一个错误,至少对我来说。(也许我做错了。它告诉图像需要是位图)
如果可能的话,我想避免自定义渲染器,因为现在它在没有任何自定义渲染的情况下运行得很好(除了我所说的某些颜色)。
如果您不想使用自定义渲染器,Xamarin Forms 地图标记/图钉只有 300 多种颜色可供使用。
但是,如果您想按照您希望的方式表示标记/图钉颜色,则需要实现Xamarin Forms 自定义渲染器来实现/捕获您想要的确切标记/图钉颜色。
按照 Xamarin Forms 自定义呈现器文档中的步骤操作后,重写以下方法:
protected override MarkerOptions CreateMarker(Pin pin)
{
CustomPin customPin = (CustomPin)pin;
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(GetCustomBitmapDescriptor(customPin.Color));
return marker;
}
Run Code Online (Sandbox Code Playgroud)
然后我创建了以下方法,将对标记/图钉颜色进行实际更改,这些颜色将与 RGB/十六进制颜色代码中的颜色完全相同:
private BitmapDescriptor GetCustomBitmapDescriptor(string text)
{
using (Paint paint = new Paint(PaintFlags.AntiAlias))
{
using (Rect bounds = new Rect())
{
using (Bitmap baseBitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.marker))
{
Bitmap resultBitmap = Bitmap.CreateBitmap(baseBitmap, 0, 0, baseBitmap.Width - 1, baseBitmap.Height - 1);
Paint p = new Paint();
ColorFilter filter = new PorterDuffColorFilter(Android.Graphics.Color.ParseColor(text), PorterDuff.Mode.SrcAtop);
p.SetColorFilter(filter);
Canvas canvas = new Canvas(resultBitmap);
canvas.DrawBitmap(resultBitmap, 0, 0, p);
Bitmap scaledImage = Bitmap.CreateScaledBitmap(resultBitmap, 94, 150, false);
BitmapDescriptor icon = BitmapDescriptorFactory.FromBitmap(scaledImage);
resultBitmap.Recycle();
return (icon);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
笔记:
此示例代码仅适用于 Android。不确定是否适用于 iOS。
Resource.Drawable.marker 可以是您可以使用的任何标记。我刚刚在网上下载了一个通用的红色地图标记。无论如何,它都会被 GetCustomBitmapDescriptor 方法覆盖。
resultBitmap.Recycle(); 非常重要。由于位图占用大量内存,并且设备应用程序可能会停止,因此您需要重用位图内存。
CustomPin 是扩展 Xamarin.Forms.Map.Pin 类的类。我为标记引脚所需颜色的字符串十六进制值添加了一个字符串属性。
查看具有自定义颜色的地图示例图像。
| 归档时间: |
|
| 查看次数: |
3401 次 |
| 最近记录: |