In the actual development, we often encounter such a demand, that is, no matter what the picture looks like, we want it to show round, round with a border, rectangle and border, with rounded rectangles and so on, I have my usual components and demo uploaded to GitHub (https://github.com/ Mapleyuan/roundimageview), the effect is as follows. Everyone is interested can be down to use, found that there is any problem also welcome to me.
I'll probably talk about the implementation below.
The first of course is inheriting ImageView, overriding the OnDraw () method. Let's take a look at the implementation of OnDraw:
protected void OnDraw (canvas canvas) {
Canvas.save ();
DrawPath ();
Canvas.clippath (MPath);
Super.ondraw (canvas);
Canvas.restore ();
Drawcanvas (canvas);
}
We call a method of drawing the area first, then look at the implementation of this method:
private void DrawPath () {
....................................................
Omit non-critical parts
....................................................
Case CIRCLE:
float R = math.min (width, height)/2;
Mpath.reset ();
Mpath.addcircle (WIDTH/2, HEIGHT/2, R, Path.Direction.CW);
Mpath.close ();
Break
....................................................
Omit non-critical parts
....................................................
}
As you can see, the Addcircle method is called and a circle is drawn clockwise. Back to the OnDraw method, the canvas's Clippath method was called to crop the view, and then the drawing would be equivalent to covering a layer of masks. OK, here we have achieved a round head. If you're not satisfied with this, like adding a border,
Continue to look down and find the Drawcanvas method called
private void Drawcanvas (canvas canvas) {
int width = getwidth ();
int height = getheight ();
if (mborderwidth <= 0) {
Return
}
Mborderpaint.setcolor (Mbordercolor);
Mborderpaint.setstrokewidth (Mborderwidth);
Mborderpaint.setstyle (Paint.Style.STROKE);
Mborderpaint.setantialias (TRUE);
....................................................
Omit non-critical parts
....................................................
Case CIRCLE:
float R = math.min (width, height)/2;
Canvas.drawcircle (WIDTH/2, HEIGHT/2, R-MBORDERWIDTH/2, Mborderpaint);
Break
....................................................
Omit non-critical parts
....................................................
}
Draw a circle in the canvas by setting the width, color, and finally the brush. At this point, we basically implement the circular imgeview function, similar to other shapes. More code details Welcome to GitHub (Https://github.com/mapleyuan/RoundImageView) and welcome to the point of concern. Follow-up will be the usual common components put up, welcome to follow the download, thank you ~
Several lines of implementation of the round head, as well as some common requirements shape custom ImageView components