在Android中如何使用clipPath()方法實現簡單的裁剪圓形圖片
阿新 • • 發佈:2019-01-25
裁剪圓形圖片的方式有很多,這篇文章主要為大家介紹如何使用clipPath()方法裁剪圓形圖片。
首先,我們先看效果圖:
裁剪前:
裁剪後:
接下來,我們來一步一步的實現。
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() / 2, mBitmap.getHeight() / 2, mBitmap.getWidth() / 2, Path.Direction.CCW);
canvas.clipPath(mPath);
canvas.drawBitmap(mBitmap, 0, 0, paint);
}
}
至此,簡單的圓形圖片的裁剪已全部完成。