Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > ImageView 绘制圆环

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

作者:

本篇文章是对Android中在ImageView上绘制圆环的方法进行了详细的分析介绍,需要的朋友参考下
绘制圆环其实很简单,有大概以下三种思路. 这里先说网上提到的一种方法。思路是先绘制内圆,然后绘制圆环(圆环的宽度就是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;&nbsp;
 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); //消除锯齿
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.paint.setStyle(Style.STROKE);  //绘制空心圆或 空心矩形
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @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);   //圆环宽度

  // 第一种方法绘制圆环
  //绘制内圆
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.paint.setARGB(255, 138, 43, 226);
  this.paint.setStrokeWidth(2);
  canvas.drawCircle(center, center, innerCircle, this.paint);&nbsp;  

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //绘制圆环
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.paint.setARGB(255, 138, 43, 226);
  this.paint.setStrokeWidth(ringWidth);
  canvas.drawCircle(center, center, innerCircle + 1 +ringWidth/2, this.paint);&nbsp;  

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //绘制外圆&nbsp;
  this.paint.setARGB(255, 138, 43, 226);
  this.paint.setStrokeWidth(2);
  canvas.drawCircle(center, center, innerCircle + ringWidth, this.paint);&nbsp;&nbsp;  

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 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); 
 }&nbsp;
}
</SPAN>

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



您可能感兴趣的文章:
阅读全文