我希望以编程方式更改背景图像(PNG)的色调。如何在Android上完成?
答案 0 :(得分:6)
我测试了接受的答案,遗憾的是它返回了错误的结果。我从here找到并修改了这段代码,效果很好:
// hue-range: [0, 360] -> Default = 0
public static Bitmap hue(Bitmap bitmap, float hue) {
Bitmap newBitmap = bitmap.copy(bitmap.getConfig(), true);
final int width = newBitmap.getWidth();
final int height = newBitmap.getHeight();
float [] hsv = new float[3];
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
int pixel = newBitmap.getPixel(x,y);
Color.colorToHSV(pixel,hsv);
hsv[0] = hue;
newBitmap.setPixel(x,y,Color.HSVToColor(Color.alpha(pixel),hsv));
}
}
bitmap.recycle();
bitmap = null;
return newBitmap;
}
答案 1 :(得分:2)
链接的帖子有一些好主意,但用于ColorFilter的矩阵数学可能是(a)复杂的过度杀伤,以及(b)在结果颜色中引入可察觉的变化。
修改janin在此处给出的解决方案 - https://stackoverflow.com/a/6222023/1303595 - 我已将此版本基于Photoshop's 'Color' blend mode。它似乎避免了由PorterDuff.Mode.Multiply引起的图像变暗,并且非常适用于着色不饱和/人工黑色&amp;白色图像不会造成很大的反差。
/*
* Going for perceptual intent, rather than strict hue-only change.
* This variant based on Photoshop's 'Color' blending mode should look
* better for tinting greyscale images and applying an all-over color
* without tweaking the contrast (much)
* Final color = Target.Hue, Target.Saturation, Source.Luma
* Drawback is that the back-and-forth color conversion introduces some
* error each time.
*/
public void changeHue (Bitmap bitmap, int hue, int width, int height) {
if (bitmap == null) { return; }
if ((hue < 0) || (hue > 360)) { return; }
int size = width * height;
int[] all_pixels = new int [size];
int top = 0;
int left = 0;
int offset = 0;
int stride = width;
bitmap.getPixels (all_pixels, offset, stride, top, left, width, height);
int pixel = 0;
int alpha = 0;
float[] hsv = new float[3];
for (int i=0; i < size; i++) {
pixel = all_pixels [i];
alpha = Color.alpha (pixel);
Color.colorToHSV (pixel, hsv);
// You could specify target color including Saturation for
// more precise results
hsv [0] = hue;
hsv [1] = 1.0f;
all_pixels [i] = Color.HSVToColor (alpha, hsv);
}
bitmap.setPixels (all_pixels, offset, stride, top, left, width, height);
}
答案 2 :(得分:0)
如果将位图包装在ImageView
中,则有一种非常简单的方法:
ImageView circle = new ImageView(this);
circle.setImageBitmap(yourBitmap);
circle.setColorFilter(Color.RED);
我的猜测是,这比单独修改每个像素要快。