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

时间:2021-05-20

绘制圆环其实很简单,有大概以下三种思路. 这里先说网上提到的一种方法。思路是先绘制内圆,然后绘制圆环(圆环的宽度就是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);

}

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也是同理。
示例如下(底色是预览摄像头的视频):



声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章