今天在群里面有人问我怎样实现一张图片上面是圆角下面是直角?
类似于这样的图片:
之前用过RoundImageView,其实就是自定义ImageView。想了一下自己重新画一下图片不就ok了么?再给布局设置一个圆角效果。好了我们来看一下源码:
1.首先我们自定义RoundImageView继承于ImageView
public class RoundedImageView extends ImageView { /*圆角的半径,依次为左上角xy半径,右上角,右下角,左下角*/ private float[] rids = {10.0f,10.0f,10.0f,10.0f,0.0f,0.0f,0.0f,0.0f,}; public RoundedImageView(Context context) { super(context); } public RoundedImageView(Context context, AttributeSet attrs) { super(context, attrs); } public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * 画图 * by Hankkin at:2015-08-30 21:15:53 * @param canvas */ protected void onDraw(Canvas canvas) { Path path = new Path(); int w = this.getWidth(); int h = this.getHeight(); /*向路径中添加圆角矩形。radii数组定义圆角矩形的四个圆角的x,y半径。radii长度必须为8*/ path.addRoundRect(new RectF(0,0,w,h),rids,Path.Direction.CW); canvas.clipPath(path); super.onDraw(canvas); } }然后我们定义一个圆角的半径数组,依次为左上角x,y半径、右上角、右下角、左下角
接下来我们就自己画一下imageview
我们给路径添加圆角矩形,将我们定义的圆角半径设置进去,给canvas切割一下画布就可以了。imageview就画成了上面是圆角,下面是直角了。如果需要图片的四个角为不同的直角圆角,只需要改一下我们的圆角半径值就可以了。
2.然后我们再给布局设置一下圆角,
我们自定义一个round.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#fff" /> <corners android:topLeftRadius="5dp" android:topRightRadius="5dp" android:bottomRightRadius="5dp" android:bottomLeftRadius="5dp"/> </shape>设置一下上下左右的圆角半径,然后设置一下布局的background就ok了
比较简单,如果想要详细学习自定义圆角图片,推荐大家可以学习一下洪洋的
Android BitmapShader 实战 实现圆形、圆角图片
Android Xfermode 实战 实现圆形、圆角图片
这两篇文章,还是比较不错的