欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android开发笔记之:在ImageView上绘制圆环的实现方法

程序员文章站 2023-12-06 10:21:16
绘制圆环其实很简单,有大概以下三种思路. 这里先说网上提到的一种方法。思路是先绘制内圆,然后绘制圆环(圆环的宽度就是paint设置的paint.setstrokewidth...
绘制圆环其实很简单,有大概以下三种思路. 这里先说网上提到的一种方法。思路是先绘制内圆,然后绘制圆环(圆环的宽度就是paint设置的paint.setstrokewidth的宽度),最后绘制外圆。
请看核心源码:
复制代码 代码如下:

<span xmlns="http://www.w3.org/1999/xhtml">package yan.guoqi.rectphoto;
import android.content.context;
import android.graphics.canvas;
import android.graphics.color;
import android.graphics.paint;
import android.graphics.paint.style;
import android.graphics.rectf;
import android.util.attributeset;
import android.widget.imageview;
public class drawimageview extends imageview {
 private final paint paint;
 private final context context; 
 public drawimageview(context context, attributeset attrs) {
  super(context, attrs);
  // todo auto-generated constructor stub
  this.context = context;
  this.paint = new paint();
  this.paint.setantialias(true); //消除锯齿
                this.paint.setstyle(style.stroke);  //绘制空心圆或 空心矩形
              }
        @override
 protected void ondraw(canvas canvas) {
  // todo auto-generated method stub
  int center = getwidth()/2;
  int innercircle = dip2px(context, 83); //内圆半径
  int ringwidth = dip2px(context, 10);   //圆环宽度

  // 第一种方法绘制圆环
  //绘制内圆
                this.paint.setargb(255, 138, 43, 226);
  this.paint.setstrokewidth(2);
  canvas.drawcircle(center, center, innercircle, this.paint);   

                //绘制圆环
               this.paint.setargb(255, 138, 43, 226);
  this.paint.setstrokewidth(ringwidth);
  canvas.drawcircle(center, center, innercircle + 1 +ringwidth/2, this.paint);   

               //绘制外圆 
  this.paint.setargb(255, 138, 43, 226);
  this.paint.setstrokewidth(2);
  canvas.drawcircle(center, center, innercircle + ringwidth, this.paint);    

                super.ondraw(canvas);

 }
 /* 根据手机的分辨率从 dp 的单位 转成为 px(像素) */ 
 public static int dip2px(context context, float dpvalue) { 
  final float scale = context.getresources().getdisplaymetrics().density; 
  return (int) (dpvalue * scale + 0.5f); 
 } 
}
</span>

总结:
1,这种分三次来绘制的方法,可以将圆环的内圆 圆环 和外圆的颜色设成不一样的,对paint进行三次设置。还可以将绘制圆环的paint透明度设成10左右就会有圆环透明的效果。
2,三次绘制时的canvas.drawcircle圆心都是(center,center),但三次半径确实不一样的。尤其是第二次绘制圆环的时候,半径是innercircle + 1 +ringwidth/2。这里的加1是第一次外圆paint.setstrokewidth(2);宽度设成2,也就是说单条线的宽度1。后面的ringwidth/2也是同理。
示例如下(底色是预览摄像头的视频):

Android开发笔记之:在ImageView上绘制圆环的实现方法