如何在Android的位图中改变特定像素的颜色

15
我有一个位图,想要改变其中的某些像素。我已经将位图数据存入数组中,但如何在该数组中设置像素的颜色?
谢谢。
int[] pixels = new int[myBitmap.getHeight()*myBitmap.getWidth()];
            myBitmap.getPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());

            for(int i =0; i<500;i++){
                //Log.e(TAG, "pixel"+i +pixels[i]);
1个回答

27

要设置pixels数组中像素的颜色,请从Android的Color类的静态方法中获取值,并将它们分配到您的数组中。完成后,使用setPixels将像素复制回位图。

例如,要将位图的前五行变为蓝色:

import android.graphics.Color;

int[] pixels = new int[myBitmap.getHeight()*myBitmap.getWidth()];
myBitmap.getPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
for (int i=0; i<myBitmap.getWidth()*5; i++)
    pixels[i] = Color.BLUE;
myBitmap.setPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
您可以使用setPixel()方法逐个设置Bitmap对象中像素的颜色,而无需设置像素缓冲区。
myBitmap.setPixel(x, y, Color.rgb(45, 127, 0));

1
如何获取所有像素。 - Sheychan
@Sheychan 如果我理解得不错的话,BHSPitMonkey 首先创建一个大小等于像素总数的空像素数组。然后 myBitmap 是从 drawable 转换成位图得到的一些位图。myBitmap.getPixels 的第一个参数 pixels 就是我们刚刚创建的数组,最后这个像素数组将被更新为 myBitmap 存储的颜色。 - Raii

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接