Android - 从方形位图剪切圆圈

时间:2012-11-08 09:00:09

标签: android

我正在尝试使用以下代码从方形位图中剪切圆圈

        Canvas canvas=new Canvas(bitmapimg );
        int circleXCoord = bitmapimg .getWidth() / 2;
        int circleYCoord = bitmapimg .getHeight() / 2;
        int circleRadius = bitmapimg .getWidth() / 2;

        Rect rect = new Rect(circleXCoord - circleRadius, circleYCoord - circleRadius, circleXCoord + circleRadius, circleYCoord + circleRadius);

        int width = rect.width();
        int height = rect.height();

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLUE);
        canvas.drawRect(rect, paint);
        canvas.drawBitmap(bitmapimg , rect, rect, paint);
        Path p = new Path();
        p.addCircle(circleXCoord, circleYCoord, width / 2F, Path.Direction.CW);
        canvas.clipPath(p, Region.Op.DIFFERENCE);
        canvas.drawColor(0, PorterDuff.Mode.CLEAR);

我们的想法是将一个方形(矩形)位图附加到画布上,然后剪切一个圆形路径。清除矩形和圆形之间的差异(使其透明)。

该代码适用于Android 4,但在Android 2.3.3设备上,差异区域显示为黑色而非透明。

我在这里遗漏了什么或姜饼不支持PorterDuff.Mode.CLEAR吗?有没有更好的方法从Android中的方块切割圆圈?

2 个答案:

答案 0 :(得分:38)

看起来像PorterDuff.Mode.Clear不适用于姜饼

解决了问题(使用此代码从正方形切圆)

 public Bitmap BitmapCircularCroper(Bitmap bitmapimg){
    Bitmap output = Bitmap.createBitmap(bitmapimg.getWidth(),
            bitmapimg.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmapimg.getWidth(),
            bitmapimg.getHeight());

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawCircle(bitmapimg.getWidth() / 2,
            bitmapimg.getHeight() / 2, bitmapimg.getWidth() / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmapimg, rect, rect, paint);
    return output;

}

答案 1 :(得分:3)

import android.graphics.PorterDuff.Mode;
import android.graphics.Bitmap.Config;

public static Bitmap getCircularBitmap(Bitmap bitmap) 
{
    Bitmap output;

    if (bitmap.getWidth() > bitmap.getHeight()) {
        output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Config.ARGB_8888);
    } else {
        output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

    float r = 0;

    if (bitmap.getWidth() > bitmap.getHeight()) {
        r = bitmap.getHeight() / 2;
    } else {
        r = bitmap.getWidth() / 2;
    }

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawCircle(r, r, r, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
}