在Android中如何使用clipPath()方法实现简单的裁剪圆形图片

xiaoxiao2021-02-28  67

裁剪圆形图片的方式有很多,这篇文章主要为大家介绍如何使用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); } }

至此,简单的圆形图片的裁剪已全部完成。

转载请注明原文地址: https://www.6miu.com/read-48508.html

最新回复(0)