1. Custom properties, create a new Attrs file under the value folder, declare the following properties
<declare-styleable name= "Circleimageview" > <attr name= "border_color" format= "color"/> < attr name= "Border_width" format= "Dimension"/></declare-styleable>
2. Inheriting ImageView, overriding construction and OnDraw methods
Public classCircleimageviewextendsAppcompatimageview {Private intbordercolor; Private intBorderWidth; Private Final Static intDefault_color =Color.Black; Private Final Static intDefault_border_width = 0; PrivatePaint Mpaint; PublicCircleimageview (Context context) { This(Context,NULL); } PublicCircleimageview (Context context, @Nullable AttributeSet attrs) { This(Context, attrs,0); } PublicCircleimageview (context context, @Nullable AttributeSet attrs,intdefstyleattr) { Super(context, attrs, defstyleattr); TypedArray TypedArray=context.obtainstyledattributes (Attrs,r.styleable.circleimageview); BorderColor=Typedarray.getcolor (R.styleable.circleimageview_border_color, Default_color); BorderWidth=typedarray.getdimensionpixelsize (R.styleable.circleimageview_border_width, default_border_width); BorderWidth=dp2px (context,borderwidth); Mpaint=NewPaint (); Typedarray.recycle (); } Public intDP2PX (Context CTX,intDP) { floatScale =ctx.getresources (). Getdisplaymetrics (). density; return(int) (DP * scale + 0.5); } @Overrideprotected voidOnDraw (canvas canvas) {drawable drawable=getdrawable (); if(Drawable! =NULL) {Bitmap Bitmap=((bitmapdrawable) drawable). Getbitmap (); Bitmap Circlebitmap=Getcirclebitmap (bitmap); Rect srcrect=NewRect (0,0, Circlebitmap.getwidth (), Circlebitmap.getheight ()); Rect Dstrect=NewRect (0,0, GetWidth (), getheight ()); Mpaint.reset (); Canvas.drawbitmap (Circlebitmap,srcrect,dstrect,mpaint); }Else { Super. OnDraw (canvas); } } PrivateBitmap Getcirclebitmap (Bitmap Bitmap) {Bitmap Circlebitmap=Bitmap.createbitmap (Bitmap.getwidth (), Bitmap.getheight (), Bitmap.Config.ARGB_8888); Canvas Canvas=NewCanvas (CIRCLEBITMAP); Mpaint.setantialias (true); Canvas.drawargb (0,255,255,255); Mpaint.setcolor (bordercolor); intRadius = Bitmap.getwidth () < Bitmap.getheight ()?bitmap.getwidth (): Bitmap.getheight (); Canvas.drawcircle (RADIUS/2,radius/2,radius/2-borderwidth,mpaint); Mpaint.setxfermode (NewPorterduffxfermode (PorterDuff.Mode.SRC_IN)); Rect rect=NewRect (0,0, Bitmap.getwidth (), Bitmap.getheight ()); Canvas.drawbitmap (Bitmap,rect,rect,mpaint); Mpaint.setxfermode (NewPorterduffxfermode (PorterDuff.Mode.DST_OVER)); Canvas.drawcircle (RADIUS/2,radius/2,radius/2, Mpaint); returnCirclebitmap; }}
3. Introduction of Circleimageview
<com.mydemo.view.circleimageview android:layout_width= "100DP" android:layout_height= "100DP" android:src= "@drawable/logo" app:border_color= "#ffff00" app:border_width= "1DP" />
Android Development Round ImageView implementation