It is actually very easy to draw a ring. There are three ideas below. Here we will talk about one of the methods mentioned on the Internet. The idea is to first draw the incircle, then draw the ring (the ring width is the width of the paint. setStrokeWidth set by the paint), and finally draw the outer circle.
Please refer to the core source code:
Copy codeThe Code is as follows: <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); // eliminate the Sawtooth
This. paint. setStyle (Style. STROKE); // draw a hollow circle or a hollow rectangle.
}
@ Override
Protected void onDraw (Canvas canvas ){
// TODO Auto-generated method stub
Int center = getWidth ()/2;
Int innerCircle = dip2px (context, 83); // inner circle radius
Int ringWidth = dip2px (context, 10); // Ring Width
// Method 1
// Draw incircle
This. paint. setARGB (255,138, 43,226 );
This. paint. setStrokeWidth (2 );
Canvas. drawCircle (center, center, innerCircle, this. paint );
// Draw a ring
This. paint. setARGB (255,138, 43,226 );
This. paint. setStrokeWidth (ringWidth );
Canvas. drawCircle (center, center, innerCircle + 1 + ringWidth/2, this. paint );
// Draw the outer circle
This. paint. setARGB (255,138, 43,226 );
This. paint. setStrokeWidth (2 );
Canvas. drawCircle (center, center, innerCircle + ringWidth, this. paint );
Super. onDraw (canvas );
}
/* Convert the unit of dp to px (pixel) based on the resolution of the mobile phone )*/
Public static int dip2px (Context context, float dpValue ){
Final float scale = context. getResources (). getDisplayMetrics (). density;
Return (int) (dpValue * scale + 0.5f );
}
}
</SPAN>
Summary:
1. This method of drawing by three times can set the color of the incircle and excircle of the ring to different, and set the paint three times. You can also set the paint transparency of the ring to about 10 to make the ring transparent.
2. The center of the canvas. drawCircle is (center, center), but the three radius is indeed different. Especially when the ring is drawn for the second time, the radius is innerCircle + 1 + ringWidth/2. Here, 1 is the first external circle paint. setStrokeWidth (2); the width is set to 2, that is, the width of a single line is 1. The same is true for the following ringWidth/2.
The following is an example (the background color is the video of the preview camera ):