一、问题在哪里?
问题来源于app开发中一个很常见的场景――用户头像要展示成圆的:
二、怎么搞?
机智的我,第一想法就是,切一张中间圆形透明、四周与底色相同、尺寸与头像相同的蒙板图片,盖在头像上不就完事了嘛,哈哈哈!
在背景纯色的前提下,这的确能简单解决问题,但是如果背景没有这么简单呢?
在这种不规则背景下,有两个问题:
1)、背景图常常是适应手机宽度缩放,而头像的尺寸又是固定宽高DP的,所以固定的蒙板图片是没法保证在不同机型上都和背景图案吻合的。
2)、在这种非纯色背景下,哪天想调整一下头像位置就得重新换图片蒙板,实在是太难维护了……
所以呢,既然头像图片肯定是方的,那就就让ImageVIEw圆起来吧。
三、开始干活
基本思路是,自定义一个ImageVIEw,通过重写onDraw方法画出一个圆形的图片来:
public class ImageVIEwPlus extends ImageVIEw{ private Paint mPaintBitmap = new Paint(Paint.ANTI_AliAS_FLAG); private Bitmap mRawBitmap; private BitmapShader mShader; private Matrix mMatrix = new Matrix(); public ImageVIEwPlus(Context context,AttributeSet attrs) { super(context,attrs); } @OverrIDe protected voID onDraw(Canvas canvas) { Bitmap rawBitmap = getBitmap(getDrawable()); if (rawBitmap != null){ int vIEwWIDth = getWIDth(); int vIEwHeight = getHeight(); int vIEwMinSize = Math.min(vIEwWIDth,vIEwHeight); float dstWIDth = vIEwMinSize; float dstHeight = vIEwMinSize; if (mShader == null || !rawBitmap.equals(mRawBitmap)){ mRawBitmap = rawBitmap; mShader = new BitmapShader(mRawBitmap,TileMode.CLAMP,TileMode.CLAMP); } if (mShader != null){ mMatrix.setScale(dstWIDth / rawBitmap.getWIDth(),dstHeight / rawBitmap.getHeight()); mShader.setLocalMatrix(mMatrix); } mPaintBitmap.setShader(mShader); float radius = vIEwMinSize / 2.0f; canvas.drawCircle(radius,radius,mPaintBitmap); } else { super.onDraw(canvas); } } private Bitmap getBitmap(Drawable drawable){ if (drawable instanceof BitmapDrawable){ return ((BitmapDrawable)drawable).getBitmap(); } else if (drawable instanceof colorDrawable){ Rect rect = drawable.getBounds(); int wIDth = rect.right - rect.left; int height = rect.bottom - rect.top; int color = ((colorDrawable)drawable).getcolor(); Bitmap bitmap = Bitmap.createBitmap(wIDth,height,Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.drawARGB(color.Alpha(color),color.red(color),color.green(color),color.blue(color)); return bitmap; } else { return null; } }}
分析一下代码:
canvas.drawCircle 决定了画出来的形状是圆形,而圆形的内容则是通过 mPaintBitmap.setShader 搞定的。
其中,BitmapShader需要设置Bitmap填充ImageVIEw的方式(CLAMP:拉伸边缘,MIRROR:镜像,REPEAT:整图重复)。
这里其实设成什么不重要,因为我们实际需要的是将Bitmap按比例缩放成跟ImageVIEw一样大,而不是预置的三种效果。
所以,别忘了 mMatrix.setScale 和 mShader.setLocalMatrix 一起用,将图片缩放一下。
四、更多玩法 ―― 支持边框
看下面的效果图,如果想给圆形的头像上加一个边框,该怎么搞呢?
public class ImageVIEwPlus extends ImageVIEw{ private Paint mPaintBitmap = new Paint(Paint.ANTI_AliAS_FLAG); private Paint mPaintborder = new Paint(Paint.ANTI_AliAS_FLAG); private Bitmap mRawBitmap; private BitmapShader mShader; private Matrix mMatrix = new Matrix(); private float mborderWIDth = dip2px(15); private int mbordercolor = 0xFF0080FF; public ImageVIEwPlus(Context context,TileMode.CLAMP); } if (mShader != null){ mMatrix.setScale((dstWIDth - mborderWIDth * 2) / rawBitmap.getWIDth(),(dstHeight - mborderWIDth * 2) / rawBitmap.getHeight()); mShader.setLocalMatrix(mMatrix); } mPaintBitmap.setShader(mShader); mPaintborder.setStyle(Paint.Style.stroke); mPaintborder.setstrokeWIDth(mborderWIDth); mPaintborder.setcolor(mbordercolor); float radius = vIEwMinSize / 2.0f; canvas.drawCircle(radius,radius - mborderWIDth / 2.0f,mPaintborder); canvas.translate(mborderWIDth,mborderWIDth); canvas.drawCircle(radius - mborderWIDth,radius - mborderWIDth,color.blue(color)); return bitmap; } else { return null; } } private int dip2px(int dipVal) { float scale = getResources().getdisplayMetrics().density; return (int)(dipVal * scale + 0.5f); }}
看代码中,加边框实际上就是用实心纯色的 Paint 画了一个圆边,在此基础上画上原来的头像即可。
需要的注意的地方有三个:
1)、圆框的半径不是 radius ,而应该是 radius - mborderWIDth / 2.0f 。想象着拿着笔去画线,线其实是画在右图中白色圈的位置,只不过它很粗。
2)、在ImageVIEw大小不变的基础上,头像的实际大小要比没有边框的时候小了,所以 mMatrix.setScale 的时候要把边框的宽度去掉。
3)、画头像Bitmap的时候不能直接 canvas.drawCircle(radius,mPaintBitmap) ,这样你会发现头像的右侧和下方边缘被拉伸了(右图)
为什么呢?因为 Paint 默认是以左上角为基准开始绘制的,此时头像的实际区域是右图中的红框,而超过红框的部分(圆形的右侧和下方),自然被 TileMode.CLAMP效果沿边缘拉伸了。
所以,需要通过挪动坐标系的位置和调整圆心,才能把头像画在正确的区域(右图绿框)中。
五、更多玩法 ―― 支持xml配置
既然有了边框,那如果想配置边框的宽度和颜色该如何是好呢?
基本上两个思路:
1)、给ImageVIEwPlus加上set接口,设置完成之后通过 invalIDate(); 重绘一下即可;
2)、在xml里就支持配置一些自定义属性,这样用起来会方便很多。
这里重点说一下支持xml配置自定义属性。
自定义控件要支持xml配置自定义属性的话,首先需要在 \res\values 里去定义属性:
<?xml version="1.0" enCoding="utf-8"?> <resources> <attr name="bordercolor" format="color" /> <attr name="borderWIDth" format="dimension" /> <declare-styleable name="ImageVIEwPlus"> <attr name="bordercolor" /> <attr name="borderWIDth" /> </declare-styleable> </resources>
然后在ImageVIEwPlus的构造函数中去读取这些自定义属性:
private static final int DEFAulT_border_color = color.transparent; private static final int DEFAulT_border_WIDTH = 0; public ImageVIEwPlus(Context context,attrs); //取xml文件中设定的参数 TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.ImageVIEwPlus); mbordercolor = ta.getcolor(R.styleable.ImageVIEwPlus_bordercolor,DEFAulT_border_color); mborderWIDth = ta.getDimensionPixelSize(R.styleable.ImageVIEwPlus_borderWIDth,dip2px(DEFAulT_border_WIDTH)); ta.recycle(); }
在xml布局中使用自定义属性:
<relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" xmlns:snser="http://schemas.androID.com/apk/res/cc.snser.imagevIEwplus" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:background="@drawable/wallpaper" androID:orIEntation="vertical" tools:context="${relativePackage}.${activityClass}" > <cc.snser.imagevIEwplus.ImageVIEwPlus androID:ID="@+ID/imgplus" androID:layout_wIDth="200dp" androID:layout_height="300dp" androID:layout_marginBottom="50dp" androID:layout_centerHorizontal="true" androID:layout_alignParentBottom="true" androID:src="@drawable/img_square" snser:bordercolor="#FF0080FF" snser:borderWIDth="15dp" /> </relativeLayout>
六、更多玩法 ―― 圆角imageview
搞定了圆形ImageVIEw以及对应的边框,那如何实现下面这种圆角的ImageVIEw呢?
其实原理上一样,把 canvas.drawCircle 对应改成 canvas.drawRoundRect 就OK了,直接贴代码吧:
public class ImageVIEwPlus extends ImageVIEw{ /** * androID.Widget.ImageVIEw */ public static final int TYPE_NONE = 0; /** * 圆形 */ public static final int TYPE_CIRCLE = 1; /** * 圆角矩形 */ public static final int TYPE_ROUNDED_RECT = 2; private static final int DEFAulT_TYPE = TYPE_NONE; private static final int DEFAulT_border_color = color.transparent; private static final int DEFAulT_border_WIDTH = 0; private static final int DEFAulT_RECT_ROUND_RADIUS = 0; private int mType; private int mbordercolor; private int mborderWIDth; private int mRectRoundRadius; private Paint mPaintBitmap = new Paint(Paint.ANTI_AliAS_FLAG); private Paint mPaintborder = new Paint(Paint.ANTI_AliAS_FLAG); private RectF mRectborder = new RectF(); private RectF mRectBitmap = new RectF(); private Bitmap mRawBitmap; private BitmapShader mShader; private Matrix mMatrix = new Matrix(); public ImageVIEwPlus(Context context,R.styleable.ImageVIEwPlus); mType = ta.getInt(R.styleable.ImageVIEwPlus_type,DEFAulT_TYPE); mbordercolor = ta.getcolor(R.styleable.ImageVIEwPlus_bordercolor,dip2px(DEFAulT_border_WIDTH)); mRectRoundRadius = ta.getDimensionPixelSize(R.styleable.ImageVIEwPlus_rectRoundRadius,dip2px(DEFAulT_RECT_ROUND_RADIUS)); ta.recycle(); } @OverrIDe protected voID onDraw(Canvas canvas) { Bitmap rawBitmap = getBitmap(getDrawable()); if (rawBitmap != null && mType != TYPE_NONE){ int vIEwWIDth = getWIDth(); int vIEwHeight = getHeight(); int vIEwMinSize = Math.min(vIEwWIDth,vIEwHeight); float dstWIDth = mType == TYPE_CIRCLE ? vIEwMinSize : vIEwWIDth; float dstHeight = mType == TYPE_CIRCLE ? vIEwMinSize : vIEwHeight; float halfborderWIDth = mborderWIDth / 2.0f; float doubleborderWIDth = mborderWIDth * 2; if (mShader == null || !rawBitmap.equals(mRawBitmap)){ mRawBitmap = rawBitmap; mShader = new BitmapShader(mRawBitmap,TileMode.CLAMP); } if (mShader != null){ mMatrix.setScale((dstWIDth - doubleborderWIDth) / rawBitmap.getWIDth(),(dstHeight - doubleborderWIDth) / rawBitmap.getHeight()); mShader.setLocalMatrix(mMatrix); } mPaintBitmap.setShader(mShader); mPaintborder.setStyle(Paint.Style.stroke); mPaintborder.setstrokeWIDth(mborderWIDth); mPaintborder.setcolor(mborderWIDth > 0 ? mbordercolor : color.transparent); if (mType == TYPE_CIRCLE){ float radius = vIEwMinSize / 2.0f; canvas.drawCircle(radius,radius - halfborderWIDth,mPaintborder); canvas.translate(mborderWIDth,mborderWIDth); canvas.drawCircle(radius - mborderWIDth,mPaintBitmap); } else if (mType == TYPE_ROUNDED_RECT){ mRectborder.set(halfborderWIDth,halfborderWIDth,dstWIDth - halfborderWIDth,dstHeight - halfborderWIDth); mRectBitmap.set(0.0f,0.0f,dstWIDth - doubleborderWIDth,dstHeight - doubleborderWIDth); float borderRadius = mRectRoundRadius - halfborderWIDth > 0.0f ? mRectRoundRadius - halfborderWIDth : 0.0f; float bitmapRadius = mRectRoundRadius - mborderWIDth > 0.0f ? mRectRoundRadius - mborderWIDth : 0.0f; canvas.drawRoundRect(mRectborder,borderRadius,mborderWIDth); canvas.drawRoundRect(mRectBitmap,bitmapRadius,mPaintBitmap); } } else { super.onDraw(canvas); } } private int dip2px(int dipVal) { float scale = getResources().getdisplayMetrics().density; return (int)(dipVal * scale + 0.5f); } private Bitmap getBitmap(Drawable drawable){ if (drawable instanceof BitmapDrawable){ return ((BitmapDrawable)drawable).getBitmap(); } else if (drawable instanceof colorDrawable){ Rect rect = drawable.getBounds(); int wIDth = rect.right - rect.left; int height = rect.bottom - rect.top; int color = ((colorDrawable)drawable).getcolor(); Bitmap bitmap = Bitmap.createBitmap(wIDth,color.blue(color)); return bitmap; } else { return null; } }}
<relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" xmlns:snser="http://schemas.androID.com/apk/res/cc.snser.imagevIEwplus" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:background="@drawable/wallpaper" androID:orIEntation="vertical" tools:context="${relativePackage}.${activityClass}" > <cc.snser.imagevIEwplus.ImageVIEwPlus androID:ID="@+ID/imgplus" androID:layout_wIDth="200dp" androID:layout_height="300dp" androID:layout_marginBottom="50dp" androID:layout_centerHorizontal="true" androID:layout_alignParentBottom="true" androID:src="@drawable/img_rectangle" snser:type="rounded_rect" snser:bordercolor="#FF0080FF" snser:borderWIDth="10dp" snser:rectRoundRadius="30dp" /> </relativeLayout>
<?xml version="1.0" enCoding="utf-8"?> <resources> <attr name="type"> <enum name="none" value="0" /> <enum name="circle" value="1" /> <enum name="rounded_rect" value="2" /> </attr> <attr name="bordercolor" format="color" /> <attr name="borderWIDth" format="dimension" /> <attr name="rectRoundRadius" format="dimension" /> <declare-styleable name="ImageVIEwPlus"> <attr name="type" /> <attr name="bordercolor" /> <attr name="borderWIDth" /> <attr name="rectRoundRadius" /> </declare-styleable></resources>
七、Demo源码
Android自定义圆形ImageView
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
以上是内存溢出为你收集整理的Android自定义控件之圆形、圆角ImageView全部内容,希望文章能够帮你解决Android自定义控件之圆形、圆角ImageView所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)