Android Bitmap - 将圆圈裁剪成半圆形

时间:2016-03-30 20:15:20

标签: java android canvas graphics bitmap

我正在尝试使用android canvas将圆圈切成半圆形。使用Bitmap类加载圆圈。

以下是示例:

enter image description here

我一直在寻找任何解决方案,尤其是能够使用坐标裁剪位图的解决方案,但无济于事。

感谢任何帮助,谢谢......

1 个答案:

答案 0 :(得分:1)

之前我遇到了同样的挑战,我以一种简单的方式解决了它,主要的想法很简单!使用位图掩码,使用最高整数值(0xFFFFFFFF)填充要保存的像素(在本例中为饼图),这样您就可以使用按位AND来获得结果颜色,蒙版Bitmap的其他像素将是透明黑色(0x00000000),当您完成蒙版时,创建结果Bitmap并按照以下方法填充像素:< / p>

public Bitmap applyPieMask(Bitmap src, float startAngle, float sweepAngle) {
    int width = src.getWidth();
    int height = src.getHeight();

    //create bitmap mask with the same dimension of the src bitmap
    Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(mask);
    canvas.drawColor(0x00000000);//fill mask bitmap with transparent black!

    //init mask paint
    Paint maskPaint = new Paint();
    maskPaint.setColor(0xFFFFFFFF);//pick highest value for bitwise AND operation
    maskPaint.setAntiAlias(true);

    //choose entire bitmap as a rect
    RectF rect = new RectF(0, 0, width, height);
    canvas.drawArc(rect, startAngle, sweepAngle, true, maskPaint);//mask the pie


    Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            //combine src color and mask to gain the result color
            int color = mask.getPixel(i, j) & src.getPixel(i, j);
            result.setPixel(i, j, color);
        }
    }
    return result;
}

我们走了......

public void doIt(View view) {

    ImageView imageView = (ImageView) findViewById(R.id.iv);
    Bitmap src = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(src);
    canvas.drawColor(Color.BLUE);//fill src bitmap with blue color
    imageView.setImageBitmap(applyPieMask(src, -90, 60));
}

enter image description here

希望你觉得有用