Android & cut (remove) shape from bitmap

2019-04-09 02:18发布

问题:

How do you cut (remove) a section from a bitmap??? I want that section/shape to be removed.. leave transparent in place of section.. Say shape is cercle or square..

回答1:

You should be able do this with a Porter-Duff color filter and a Canvas:

public void punchHole(Bitmap bitmap, float cx, float cy, float radius) {
    Canvas c = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setColorFilter(new PorderDuffColorFilter(0, PorderDuff.Mode.CLEAR));
    c.drawCircle(cx, cy, radius, paint);
}

Well, that was wrong. However, using a Porter-Duff transfer mode does work:

public void punchHole(Bitmap bitmap, float cx, float cy, float radius) {
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    canvas.drawCircle(cx, cy, radius, paint);
}

(The bitmap passed as an arg needs to be modifiable, of course.)



回答2:

Use Bitmap.setPixel(x,y,Color) function to set the desired pixels to transparent

for example:

Bitmap bmp = ...;
bmp.setPixel (100,100,Color.TRANSPARENT);

for the pixel at x/y offset 100,100. Though you'll find this potentially slow to do this on many pixels...



回答3:

Did you try drawing a circle with a transparent color, ARGB = 0,0,0,0 ?