天天看點

在Android中如何使用clipPath()方法實作簡單的裁剪圓形圖檔

裁剪圓形圖檔的方式有很多,這篇文章主要為大家介紹如何使用clipPath()方法裁剪圓形圖檔。

首先,我們先看效果圖:

裁剪前:

在Android中如何使用clipPath()方法實作簡單的裁剪圓形圖檔

裁剪後:

在Android中如何使用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() / , mBitmap.getHeight() / , mBitmap.getWidth() / , Path.Direction.CCW);
        canvas.clipPath(mPath);
        canvas.drawBitmap(mBitmap, , , paint);
    }
}
           

至此,簡單的圓形圖檔的裁剪已全部完成。