如何使用现有的位图,比如说
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.somebitmap);
并编写一个返回位图的黑暗版本的方法?
private Bitmap darkenBitMap(Bitmap bm) { }
到目前为止,我一直在尝试使用Paint和Canvas,没有任何结果。
答案 0 :(得分:25)
我终于明白了。希望它可以帮助别人。
private Bitmap darkenBitMap(Bitmap bm) {
Canvas canvas = new Canvas(bm);
Paint p = new Paint(Color.RED);
//ColorFilter filter = new LightingColorFilter(0xFFFFFFFF , 0x00222222); // lighten
ColorFilter filter = new LightingColorFilter(0xFF7F7F7F, 0x00000000); // darken
p.setColorFilter(filter);
canvas.drawBitmap(bm, new Matrix(), p);
return bm;
}
答案 1 :(得分:0)
这是一个迭代每个像素的示例。
/**
* @param bitmap a mutable bitmap instance.
*/
private void darkenBitmap(Bitmap bitmap) {
int height = bitmap.getHeight();
int width = bitmap.getWidth();
int pixel;
// Iterate over each row (y-axis)
for (int y = 0; y < height; y++) {
// and each column (x-axis) on that row
for (int x = 0; x < width; x++) {
pixel = bitmap.getPixel(x, y);
// TODO: Modify your pixel here. For samples, http://stackoverflow.com/questions/4928772/android-color-darker
bitmap.setPixel(x, y, pixel);
}
}
}
该方法需要可变位图,因此您可能需要使用BitmapFactory选项加载位图。如,
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.somebitmap, options);
你也可以在该方法中创建一个新的可变位图,在其上调用setPixel(...)并返回它。但是,如果可能的话,我强烈建议避免使用这种内存分配。
答案 2 :(得分:0)
private Bitmap darkenBitMap(Bitmap bm) {
Canvas canvas = new Canvas(bm);
canvas.drawARGB(1,0,0,0);
canvas.drawBitmap(bm, new Matrix(), new Paint());
return bm;
}
答案 3 :(得分:0)
以the_prole的答案为基础,此功能可以将较暗的位图转换为较亮的位图。您所要做的就是传递0到100之间的数字(0较暗,100较亮)。
public void grayscaleImage(Bitmap bitmap, int lighten)
{
Bitmap bmpGrayscale = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGrayscale);
Paint grayscalePaint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
grayscalePaint.setColorFilter(new ColorMatrixColorFilter(cm));
c.drawBitmap(bitmap, new Matrix(), grayscalePaint);
ArgbEvaluator evaluator = new ArgbEvaluator();
float fraction = lighten / 100.0F;
int mul = (int) evaluator.evaluate(fraction, 0xFF7F7F7F, 0xFFFFFFFF);
int add = (int) evaluator.evaluate(fraction, 0x00000000, 0x00222222);
Paint lighteningPaint = new Paint();
lighteningPaint.setColorFilter(new LightingColorFilter(mul, add));
c.drawBitmap(bmpGrayscale, new Matrix(), lighteningPaint);
setImageBitmap(bmpGrayscale);
}
答案 4 :(得分:-1)
让视图变暗。
canvas.drawARGB(200, 0, 0, 0);
简短而简单:)