android 图片剪切圆角
时间: 2023-09-05 08:14:04 浏览: 49
在Android中,可以通过自定义View的方式来实现图片剪切圆角的效果。以下是一个简单的示例代码:
1. 自定义一个RoundImageView类,继承自ImageView:
```
public class RoundImageView extends ImageView {
private Paint mPaint;
private RectF mRectF;
private float mRadius;
public RoundImageView(Context context) {
this(context, null);
}
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint();
mRectF = new RectF();
mPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
super.onDraw(canvas);
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
Bitmap roundBitmap = getRoundBitmap(bitmap, getWidth(), getHeight(), mRadius);
mPaint.reset();
canvas.drawBitmap(roundBitmap, 0, 0, mPaint);
}
private Bitmap getRoundBitmap(Bitmap bitmap, int width, int height, float radius) {
Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
mRectF.set(0, 0, width, height);
canvas.drawRoundRect(mRectF, radius, radius, mPaint);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, null, mRectF, mPaint);
return output;
}
public void setRadius(float radius) {
this.mRadius = radius;
invalidate();
}
}
```
2. 在xml布局文件中引用这个RoundImageView:
```
<com.example.RoundImageView
android:id="@+id/iv_round"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:src="@drawable/test"
app:radius="20dp"/>
```
3. 在Activity中找到这个RoundImageView,并调用setRadius()方法设置圆角半径:
```
RoundImageView roundImageView = findViewById(R.id.iv_round);
roundImageView.setRadius(20);
```
这样就可以实现在Android中对图片进行圆角剪切的效果了。