裁剪圓形圖檔的方式有很多,這篇文章主要為大家介紹如何使用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);
}
}
至此,簡單的圓形圖檔的裁剪已全部完成。