Android:如何绘制位图的单一颜色?

时间:2013-03-15 21:57:57

标签: android graphics bitmap android-canvas

我是Android的2D图形的新手,我想知道是否可以这样做:

https://dl.dropbox.com/u/6818591/pendulum_background.png

使用上面链接中的图像,我想根据我提供的角度填充特定颜色的圆圈的白色部分,保留黑色和透明部分。

我设法使用drawArc()方法制作弧线,但它覆盖了图像。由于图像中的圆弧不是一个完美的圆形,它稍微被压扁,这个问题很复杂。

有没有办法只在白色空间上画画?使用过滤器或面具?如果你有示例代码,我可以使用,这将是伟大的! :)

谢谢

2 个答案:

答案 0 :(得分:3)

试试这个

private Drawable fillBitmap(Bitmap bitimg1, int r, int g, int b) {
        Bitmap bitimg = bitimg1.copy(bitimg1.getConfig(), true);


    int a = transperentframe;
    Drawable dr = null;
    for (int x = 0; x < bitimg.getWidth(); x++) {
        for (int y = 0; y < bitimg.getHeight(); y++) {

            int pixelColor = bitimg.getPixel(x, y);
            int A = Color.alpha(pixelColor);
            bitimg.setPixel(x, y, Color.argb(A, r, g, b));
        }
    }
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitimg,
            framewidth + 10, frameheight, true);

    dr = new BitmapDrawable(getResources(), resizedBitmap);

    return dr;
}

通过使用此代码,我成功填充了非透明区域中的颜色,并保持透明区域不变。

你也可以这样检查:

if(canvasBitmap.getPixel(x, y) == Color.TRANSPARENT)

你可以比较任何颜色Color.BLUE任何根据你的需要应用其他方法。

答案 1 :(得分:1)

您可以在位图上使用canvas.drawPaint(..)来绘制特定颜色与另一个颜色。

// make a mutable copy and a canvas from this mutable bitmap
Bitmap bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(bitmap);

// get the int for the colour which needs to be removed
Paint paint = new Paint();
paint.setARGB(255, 0, 0, 0); // ARGB for the color, in this example, white
int removeColor = paint.getColor(); // store this color's int for later use

// Next, set the color of the paint to the color another color            
paint.setARGB(/*put ARGB values for color you want to change to here*/);

// then, set the Xfermode of the pain to AvoidXfermode
// removeColor is the color that will be replaced with the paint color
// 0 is the tolerance (in this case, only the color to be removed is targetted)
// Mode.TARGET means pixels with color the same as removeColor are drawn on
paint.setXfermode(new AvoidXfermode(removeColor, 0, AvoidXfermode.Mode.TARGET));

// re-draw
canvas.drawPaint(p);