热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

Android自定义控件之圆形/圆角的实现代码

这篇文章主要为大家详细介绍了Android自定义控件之圆形圆角的实现代码,感兴趣的小伙伴们可以参考一下

一、问题在哪里?

问题来源于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, 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, 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 - 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, radius - mBorderWidth / 2.0f, mPaintBorder);
  canvas.translate(mBorderWidth, mBorderWidth);
  canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, radius - mBorderWidth, 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;
 }
 }
 
 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, radius, radius - mBorderWidth, mPaintBitmap) ,这样你会发现头像的右侧和下方边缘被拉伸了(右图)

     为什么呢?因为 Paint 默认是以左上角为基准开始绘制的,此时头像的实际区域是右图中的红框,而超过红框的部分(圆形的右侧和下方),自然被 TileMode.CLAMP效果沿边缘拉伸了。

     所以,需要通过挪动坐标系的位置和调整圆心,才能把头像画在正确的区域(右图绿框)中。

五、更多玩法 —— 支持xml配置

既然有了边框,那如果想配置边框的宽度和颜色该如何是好呢?

基本上两个思路:

1)给ImageViewPlus加上set接口,设置完成之后通过 invalidate(); 重绘一下即可;

2)在xml里就支持配置一些自定义属性,这样用起来会方便很多。

这里重点说一下支持xml配置自定义属性。

自定义控件要支持xml配置自定义属性的话,首先需要在 \res\values 里去定义属性:

<&#63;xml version="1.0" encoding="utf-8"&#63;> 
 
 
 

  
 
 
  
 

View attrs_imageviewplus.xml
 然后在ImageViewPlus的构造函数中去读取这些自定义属性:

private static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT;
 private static final int DEFAULT_BORDER_WIDTH = 0;
 
 public ImageViewPlus(Context context, AttributeSet attrs) {
 super(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布局中使用自定义属性:


 
 
 



六、更多玩法 —— 圆角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, AttributeSet attrs) {
 super(context, attrs);
 //取xml文件中设定的参数
 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPlus);
 mType = ta.getInt(R.styleable.ImageViewPlus_type, DEFAULT_TYPE);
 mBorderColor = ta.getColor(R.styleable.ImageViewPlus_borderColor, DEFAULT_BORDER_COLOR);
 mBorderWidth = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_borderWidth, 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 &#63; viewMinSize : viewWidth;
  float dstHeight = mType == TYPE_CIRCLE &#63; 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, 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 &#63; mBorderColor : Color.TRANSPARENT);
  
  if (mType == TYPE_CIRCLE){
  float radius = viewMinSize / 2.0f;
  canvas.drawCircle(radius, radius, radius - halfBorderWidth, mPaintBorder);
  canvas.translate(mBorderWidth, mBorderWidth);
  canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, 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 &#63; mRectRoundRadius - halfBorderWidth : 0.0f;
  float bitmapRadius = mRectRoundRadius - mBorderWidth > 0.0f &#63; mRectRoundRadius - mBorderWidth : 0.0f;
  canvas.drawRoundRect(mRectBorder, borderRadius, borderRadius, mPaintBorder);
  canvas.translate(mBorderWidth, mBorderWidth);
  canvas.drawRoundRect(mRectBitmap, bitmapRadius, 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, 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;
 }
 }
}

View ImageViewPlus.java 


 
 
 


View layout 


<&#63;xml version="1.0" encoding="utf-8"&#63;> 
 
  
  
  
 
 
 
 
 

  
 
 
 
 
 
 

View attrs_imageviewplus.xml

以上就是本文的全部内容,希望对大家学习Android软件编程有所帮助。


推荐阅读
  • 在计算机技术的学习道路上,51CTO学院以其专业性和专注度给我留下了深刻印象。从2012年接触计算机到2014年开始系统学习网络技术和安全领域,51CTO学院始终是我信赖的学习平台。 ... [详细]
  • 本文详细介绍了如何使用PHP检测AJAX请求,通过分析预定义服务器变量来判断请求是否来自XMLHttpRequest。此方法简单实用,适用于各种Web开发场景。 ... [详细]
  • Linux 系统启动故障排除指南:MBR 和 GRUB 问题
    本文详细介绍了 Linux 系统启动过程中常见的 MBR 扇区和 GRUB 引导程序故障及其解决方案,涵盖从备份、模拟故障到恢复的具体步骤。 ... [详细]
  • 本文介绍了如何使用jQuery根据元素的类型(如复选框)和标签名(如段落)来获取DOM对象。这有助于更高效地操作网页中的特定元素。 ... [详细]
  • 本文将详细介绍如何使用剪映应用中的镜像功能,帮助用户轻松实现视频的镜像效果。通过简单的步骤,您可以快速掌握这一实用技巧。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 本文介绍如何在 Xcode 中使用快捷键和菜单命令对多行代码进行缩进,包括右缩进和左缩进的具体操作方法。 ... [详细]
  • 本文介绍了一款用于自动化部署 Linux 服务的 Bash 脚本。该脚本不仅涵盖了基本的文件复制和目录创建,还处理了系统服务的配置和启动,确保在多种 Linux 发行版上都能顺利运行。 ... [详细]
  • 在Linux系统中配置并启动ActiveMQ
    本文详细介绍了如何在Linux环境中安装和配置ActiveMQ,包括端口开放及防火墙设置。通过本文,您可以掌握完整的ActiveMQ部署流程,确保其在网络环境中正常运行。 ... [详细]
  • Android 渐变圆环加载控件实现
    本文介绍了如何在 Android 中创建一个自定义的渐变圆环加载控件,该控件已在多个知名应用中使用。我们将详细探讨其工作原理和实现方法。 ... [详细]
  • 如何在WPS Office for Mac中调整Word文档的文字排列方向
    本文将详细介绍如何使用最新版WPS Office for Mac调整Word文档中的文字排列方向。通过这些步骤,用户可以轻松更改文本的水平或垂直排列方式,以满足不同的排版需求。 ... [详细]
  • 本文总结了在使用Ionic 5进行Android平台APK打包时遇到的问题,特别是针对QRScanner插件的改造。通过详细分析和提供具体的解决方法,帮助开发者顺利打包并优化应用性能。 ... [详细]
  • 理解存储器的层次结构有助于程序员优化程序性能,通过合理安排数据在不同层级的存储位置,提升CPU的数据访问速度。本文详细探讨了静态随机访问存储器(SRAM)和动态随机访问存储器(DRAM)的工作原理及其应用场景,并介绍了存储器模块中的数据存取过程及局部性原理。 ... [详细]
  • 360SRC安全应急响应:从漏洞提交到修复的全过程
    本文详细介绍了360SRC平台处理一起关键安全事件的过程,涵盖从漏洞提交、验证、排查到最终修复的各个环节。通过这一案例,展示了360在安全应急响应方面的专业能力和严谨态度。 ... [详细]
  • 几何画板展示电场线与等势面的交互关系
    几何画板是一款功能强大的物理教学软件,具备丰富的绘图和度量工具。它不仅能够模拟物理实验过程,还能通过定量分析揭示物理现象背后的规律,尤其适用于难以在实际实验中展示的内容。本文将介绍如何使用几何画板演示电场线与等势面之间的关系。 ... [详细]
author-avatar
网族桃源rl
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有