在安卓中对位图进行圆形裁剪

3

我有一个正方形位图,在半透明圆圈下显示。用户可以触摸和拖动位图以将其定位。我想能够裁剪圆圈下面的位图的任何部分。我该怎么做?


https://dev59.com/OGct5IYBdhLWcg3wpO_H - zgc7009
这个回答解决了您的问题吗?如何在Android中从位图中裁剪圆形区域 - Vega
4个回答

13

请查看支持库中的 RoundedBitmapDrawable

您只需要提供位图和圆角半径即可。

RoundedBitmapDrawable img = RoundedBitmapDrawableFactory.create(getResources(),bitmap);
img.setCornerRadius(radius);

imageView.setImageDrawable(img);

3
如果您想让图片成为完美的圆形,可以使用 img.setCircular(true) 而不是 img.setCornerRadius(radius) - Roel
最佳答案是纯代码解决方案,无需修改XML或自定义形状。 - Themos

8
您可以使用RoundedBitmapDrawable将您的ImageView变成圆形,RoundedBitmapDrawable是一个很好用的工具。
以下是实现圆角ImageView的代码:
ImageView profilePic=(ImageView)findViewById(R.id.user_image);
//get bitmap of the image
Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),  R.drawable.large_icon);
RoundedBitmapDrawable roundedBitmapDrawable=
  RoundedBitmapDrawableFactory.create(getResources(), imageBitmap);
roundedBitmapDrawable.setCornerRadius(50.0f);
roundedBitmapDrawable.setAntiAlias(true);
profilePic.setImageDrawable(roundedBitmapDrawable);

你应该使用以下代码来代替使用固定的圆角半径:roundedBitmapDrawable.setCornerRadius(Math.min(roundedBitmapDrawable.getMinimumWidth(), roundedBitmapDrawable.getMinimumHeight())/2.0f); - crubio
1
如果你想让它成为圆形,可以使用 setCircular(true)。 - Roel

1
你可以利用 PorterDuff 的强大功能,将位图裁剪成任何形状或路径...
以下是示例:
public static Bitmap getCircular(Bitmap bm, int cornerRadiusPx) {
    int w = bm.getWidth();
    int h = bm.getHeight();

    int radius = (w < h) ? w : h;
    w = radius;
    h = radius;

    Bitmap bmOut = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmOut);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(0xff424242);

    Rect rect = new Rect(0, 0, w, h);
    RectF rectF = new RectF(rect);

    canvas.drawARGB(0, 0, 0, 0);
    canvas.drawCircle(rectF.left + (rectF.width()/2), rectF.top + (rectF.height()/2), radius / 2, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bm, rect, rect, paint);

    return bmOut;
}

2
现在最好使用“RoundedBitmapDrawable”而不是手动操作。 - tyczj

0

这里是一个示例项目的链接。它在图片上方有一个透明的正方形。您可以通过捏合缩放或拖动底部的图像来裁剪。

https://github.com/tcking/ImageCroppingView

正方形是使用画布制作的。您可以通过更改画布将其更改为任何所需的形状。希望能对您有所帮助。


@Nitesh - 我怎么才能把它改成圆形? - sara roberts

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接