这是我最终使用的方法:Drawable
位图上Canvas
并根据需要应用尽可能多的层,使用Paint
,它不仅适用于滤色镜,还适用于任何类型的图像混合。
...
Drawable myBackground = createBackground(getResources().getColor(R.color.Green));
setBackgroundDrawable(myBackground);
...
private Drawable createBackground(int color) {
Canvas canvas = new Canvas();
Bitmap buttonImage = BitmapFactory.decodeResource(getResources(), R.drawable.btn_image);
Bitmap buttonShadows = BitmapFactory.decodeResource(getResources(), R.drawable.btn_shadows);
Bitmap buttonHighLights = BitmapFactory.decodeResource(getResources(), R.drawable.btn_highlights);
Bitmap result = Bitmap.createBitmap(buttonImage.getWidth(), buttonImage.getHeight(), Bitmap.Config.ARGB_8888);
canvas.setBitmap(result);
Paint paint = new Paint();
paint.setFilterBitmap(false);
// Color
paint.setColorFilter(new PorterDuffColorFilter(color, Mode.MULTIPLY));
canvas.drawBitmap(buttonImage, 0, 0, paint);
paint.setColorFilter(null);
// Shadows
paint.setXfermode(new PorterDuffXfermode(Mode.MULTIPLY));
canvas.drawBitmap(buttonShadows, 0, 0, paint);
// HighLights
paint.setXfermode(new PorterDuffXfermode(Mode.SCREEN));
canvas.drawBitmap(buttonHighLights, 0, 0, paint);
paint.setXfermode(null);
return new BitmapDrawable(getResources(), result);
}
Caveat: setBackgroundDrawable(Drawable d)
已被弃用,同时setBackground(Drawable d)
仅从 api 16 开始可用,因此,如果您像我一样有最小目标 api-14 最大目标 api-17,则您没有“干净”的方法将可绘制对象设置为背景。我坚持使用已弃用的电话。