如何为Google Maps标记图标自定义着色?附现有代码求助
嘿,我来帮你搞定Google Maps标记图标着色的问题!你现在直接从资源加载图标的方式,要替换成自定义颜色其实有几种靠谱的方案,完全能保留你原有图标的形状,只改颜色,看你需求选就行:
方法1:用DrawableCompat着色(推荐,兼容低版本)
这个方法兼容性最好,能完美适配API 21以下的设备,步骤也清晰:
- 先获取并包装你的Drawable资源,确保低版本也能支持tint属性
- 给Drawable设置你想要的颜色滤镜
- 把Drawable转成Bitmap,再生成BitmapDescriptor给Marker用
代码示例:
// 获取Drawable并包装以兼容低版本 Drawable drawable = ContextCompat.getDrawable(context, R.drawable.my_location); drawable = DrawableCompat.wrap(drawable); // 设置目标颜色,这里用红色举例,也可以用getResources().getColor(R.color.your_custom_color) DrawableCompat.setTint(drawable, Color.parseColor("#FF0000")); // 将Drawable转为Bitmap Bitmap bitmap = Bitmap.createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888 ); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); // 转成Marker可用的BitmapDescriptor BitmapDescriptor coloredIcon = BitmapDescriptorFactory.fromBitmap(bitmap); markerOptions.icon(coloredIcon);
方法2:直接给Bitmap加颜色滤镜
如果你的图标是Bitmap格式,也可以直接给Bitmap加滤镜快速变色,代码更简洁:
// 加载原始Bitmap Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_location); // 创建颜色滤镜,用SRC_IN模式保留图标形状,只替换颜色 Paint paint = new Paint(); paint.setColorFilter(new PorterDuffColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN)); // 绘制着色后的新Bitmap Bitmap coloredBitmap = Bitmap.createBitmap( originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888 ); Canvas canvas = new Canvas(coloredBitmap); canvas.drawBitmap(originalBitmap, 0, 0, paint); // 设置给Marker BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(coloredBitmap); markerOptions.icon(icon);
方法3:矢量图直接设置Tint(如果你的图标是VectorDrawable)
如果my_location是矢量图,那操作更简单:
- 要么直接在矢量图XML的
<vector>标签里加tint="@color/your_color",一劳永逸 - 要么在代码里动态设置:
VectorDrawable vectorDrawable = (VectorDrawable) ContextCompat.getDrawable(context, R.drawable.my_location); vectorDrawable.setTint(Color.parseColor("#00FF00")); // 换成你要的颜色 // 转成BitmapDescriptor BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(drawableToBitmap(vectorDrawable)); markerOptions.icon(icon); // 工具方法:把Drawable转成Bitmap private Bitmap drawableToBitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888 ); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; }
小提示:如果你的原始图标是白色的,着色后的颜色会最准确;如果是其他颜色,新颜色会和原有颜色叠加,可能出现偏色哦!
内容的提问来源于stack exchange,提问作者Monique890
相关产品推荐
相关产品推荐

