我尝试了 Josip 的答案,但对我不起作用,无论偏移参数是 1 还是 0 - 绘制的位图只是以原始颜色出现。
然而,这确实有效:
// You have to copy the bitmap as any bitmaps loaded as drawables are immutable
Bitmap bm = ImageLoader.getInstance().loadImageSync("drawable://" + drawableId, o)
.copy(Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint();
ColorFilter filter = new PorterDuffColorFilter(ContextCompat.getColor(this, R.color.COLOR_1_DARK), PorterDuff.Mode.SRC_IN);
paint.setColorFilter(filter);
Canvas canvas = new Canvas(bm);
canvas.drawBitmap(bm, 0, 0, paint);
Update 1
虽然上面的方法运行良好并且在很多情况下都很有用,但如果您只想更改某个对象的主颜色图像视图可绘制,操作所做的,你可以使用:
imgView.setColorFilter(ContextCompat.getColor(this, R.color.COLOR_1_DARK));
如果您需要更大的灵活性或者这没有达到预期的效果,可以使用重载来更改波特达夫模式直到你得到你想要的:
imgView.setColorFilter(ContextCompat.getColor(this, R.color.COLOR_1_DARK), PorterDuff.Mode.SRC_ATOP);
Update 2
我最近遇到的另一个很好的用例是自定义 Google 地图 v2 标记图标的外观。为了使用 2 个图形来允许(例如)标记上有小/大图标,而且还可以通过动态更改这 2 个图形的颜色来在这两个图形上显示一系列颜色。就我而言,我是在一个集群渲染器因为标记也被聚类,但这可以以相同的方式与常规地图标记一起使用:
@Override
protected void onBeforeClusterItemRendered(MyClusterItem item, MarkerOptions markerOptions) {
try {
int markerColor = item.getColor();
Bitmap icon;
if (item.isFeatured()) {
// We must copy the bitmap or we get an exception "Immutable bitmap passed to Canvas constructor"
icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon_marker_large).copy(Bitmap.Config.ARGB_8888, true);
} else {
// We must copy the bitmap or we get an exception "Immutable bitmap passed to Canvas constructor"
icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon_marker_small).copy(Bitmap.Config.ARGB_8888, true);
}
Paint paint = new Paint();
ColorFilter filter = new PorterDuffColorFilter(ContextCompat.getColor(context, markerColor), PorterDuff.Mode.SRC_IN);
paint.setColorFilter(filter);
Canvas canvas = new Canvas(icon);
canvas.drawBitmap(icon, 0, 0, paint);
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
} catch (Exception ex) {
ex.printStackTrace();
}
}