裁剪圆形图片的方式有很多,这篇文章主要为大家介绍如何使用clipPath()方法裁剪圆形图片。
首先,我们先看效果图:
裁剪前:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiQ3chVEa0V3bT9CX5RXa2Fmcn9CXwczLcVmds92czlGZvwVP9EUTDZ0aRJkSwk0LcxGbpZ2LcBDM08CXlpXazRnbvZ2LcRlMMVDT2EWNvwFdu9mZvwVPVJTW1Z0RhpGZtJGcoNjW1x2RlZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39jNxYjM0ITN3ETMzgDM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
裁剪后:
接下来,我们来一步一步的实现。
1.新建一个module
2.新建一个自定义view类,继承View,并重写两参构造器和onDrawn方法
/**
* Created by zhaoxin on 17/8/31.
*/
public class MyAnimationView extends View {
public MyAnimationView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
3.新建一个布局,在布局中通过包名.类导入自定义view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.zhaoxin.mycustomviewanimation.MyAnimationView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
4.接下来就是重要的裁剪圆形图片部分
/**
* Created by zhaoxin on 17/8/31.
*/
public class MyAnimationView extends View {
private Bitmap mBitmap;
private Path mPath;
public MyAnimationView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic);
mPath = new Path();
mPath.addCircle(mBitmap.getWidth() / , mBitmap.getHeight() / , mBitmap.getWidth() / , Path.Direction.CCW);
canvas.clipPath(mPath);
canvas.drawBitmap(mBitmap, , , paint);
}
}
至此,简单的圆形图片的裁剪已全部完成。