自定义ImageView的形状

时间:2012-11-21 13:42:15

标签: android

说我有一个完全矩形的图像:
enter image description here

现在,当我在ImageView中展示时,我想要切掉一个角落,就像这样: enter image description here

如何在运行时实现这一目标?

1 个答案:

答案 0 :(得分:4)

我用这段代码解决了它:

    public static Bitmap maskImage(Context context, Bitmap original) {
            if (original == null)
                    return null;

            Bitmap result = Bitmap.createBitmap(original.getWidth(), original.getHeight(), Config.ARGB_8888);
            Canvas c = new Canvas(result);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(android.graphics.Color.WHITE);
            paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);

            Path path = new Path();
            path.moveTo(result.getWidth(), result.getHeight());
            path.lineTo(result.getWidth() - dpToPx(context, CORNERWIDTHDP), result.getHeight());
            path.lineTo(result.getWidth(), result.getHeight() - dpToPx(context, CORNERHEIGHTDP));

            path.close();

            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));

            c.drawBitmap(original, 0, 0, null);
            c.drawPath(path, paint);

            paint.setXfermode(null);
            return result;
    }