Android Custom round avatar Circleimageview support to load network image implementation code _android

Source: Internet
Author: User
Tags border color getcolor repetition static class

In Android development we often use rounded heads, which are especially troublesome if you have to do a round cut after each load. So write a custom round imageview here, directly to load the network image, so it is particularly convenient.

First on the effect chart

The Main method

1. Let custom Circleimageview inherit ImageView

/**
* Custom round avatar
* Created by Dylan on 2015/11/26 0026.
*/Public
class Circleimageview extends ImageView {
}

2. Gets the value set in the XML in the constructor method

Public Circleimageview {
super (context);
}
Public Circleimageview (context, AttributeSet attrs) {This
(context, attrs, 0);
}
Public Circleimageview (context, AttributeSet attrs, int defstyle) {
Super (context, attrs, defstyle);
Super.setscaletype (scale_type);
/**
* Gets the property declared in XML
/TypedArray a = Context.obtainstyledattributes (Attrs, R.styleable.circleimageview, Defstyle, 0)//Gets the attributes in the XML
mborderwidth = A.getdimensionpixelsize ( R.styleable.circleimageview_border_width, default_border_width);
Mbordercolor = A.getcolor (R.styleable.circleimageview_border_color, default_border_color);
A.recycle ();
Mready = true;
if (msetuppending) {
setup ();
Msetuppending = false;
}
}

3. Initialization of various parameter settings

/** * Draw a circular diagram of the initialization of the work/private void setup () {if (!mready) {msetuppending = true; return;} if (mbitmap = = null) {return;
/** * calls this method to produce a renderer (Shader) that has a bitmap painted. Bitmap the bitmap used within the renderer Tilex the tiling mode for x to draw the bitmap in. x Direction tile mode Tiley The tiling mode for y to draw the B
Itmap in. The Y-direction tile mode Tilemode: (a total of three kinds) Clamp: If the renderer exceeds the original bounds, it will replicate the range of the edge staining.
REPEAT: Horizontal and vertical repeating renderer picture, tiled.
MIRROR: Horizontal and vertical repeating renderer picture, which is not the same as the repeat repetition, he is tiled in a mirrored way.
* * Mbitmapshader = new Bitmapshader (Mbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
/** * Set Draw round brush/Mbitmappaint.setantialias (TRUE);//Set anti-aliasing Mbitmappaint.setshader (Mbitmapshader);//Graphic transform when drawing graphics
Mborderpaint.setstyle (Paint.Style.STROKE);
Mborderpaint.setantialias (TRUE);
Mborderpaint.setcolor (Mbordercolor);
Mborderpaint.setstrokewidth (Mborderwidth);
Mbitmapheight = Mbitmap.getheight ();
Mbitmapwidth = Mbitmap.getwidth ();
/** * Set the coordinates of the bounding rectangle * * Mborderrect.set (0, 0, getwidth (), getheight ()); /** * Sets the radius of the bounding circle to the maximum of half the width and height of the picture * * * Mborderradius = Math.max (mborderrect.Height ()-mborderwidth)/2, (Mborderrect.width ()-mborderwidth)/2); /** * Set the coordinates of the picture rectangle * * Mdrawablerect.set (Mborderwidth, Mborderwidth, Mborderrect.width ()-Mborderwidth, Mborderrect.height
()-mborderwidth);
/** * Set the radius of the picture circle to the maximum of half of the width and height of the picture * * * Mdrawableradius = Math.max (Mdrawablerect.height ()/2, Mdrawablerect.width ()/2);
Updateshadermatrix ();
/** * calls the OnDraw () method for painting/invalidate (); /** * Update bitmap rendering/private void Updateshadermatrix () {float scale; float dx = 0; float dy = 0;/** * Reset * * MSHADERMATRIX.S
ET (NULL);
/** * Calculates the scaling ratio, because if the picture is larger than the screen, it will automatically match the size of the screen to display. * Determine the moved XY (*/IF) (Mbitmapwidth * mdrawablerect.height () > Mdrawablerect.width () * mbitmapheight) {scale = Mdrawable
Rect.width ()/(float) mbitmapwidth;
DY = (mdrawablerect.height ()-mbitmapheight * scale) * 0.5f; else {scale = Mdrawablerect.height ()/(float) mbitmapheight dx = (mdrawablerect.width ()-mbitmapwidth * scale) * 0.5
F
} mshadermatrix.setscale (scale, scale); Mshadermatrix.posttranslate ((int) (DX + 0.5f)+ mborderwidth, (int) (dy + 0.5f) + mborderwidth);
/** * Set the local matrix of shader/Mbitmapshader.setlocalmatrix (Mshadermatrix); }

4. Draw a Circle

@Override
protected void OnDraw (Canvas Canvas) {
if (getdrawable () = null) {return
;
}
/**
* Draw round picture * * *
canvas.drawcircle (GetWidth ()/2, GetHeight ()/2, Mdrawableradius, mbitmappaint);
/**
* Draw round border * * *
canvas.drawcircle (GetWidth ()/2, GetHeight ()/2, Mborderradius, mborderpaint);

Complete code, with full comments

1.CircleImageView Main class

Import Android.content.Context;
Import Android.content.res.TypedArray;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapShader;
Import Android.graphics.Canvas;
Import Android.graphics.Color;
Import Android.graphics.Matrix;
Import Android.graphics.Paint;
Import Android.graphics.RectF;
Import Android.graphics.Shader;
Import android.graphics.drawable.BitmapDrawable;
Import android.graphics.drawable.ColorDrawable;
Import android.graphics.drawable.Drawable;
Import Android.util.AttributeSet;
Import Android.widget.ImageView;
Import COM.KEJIANG.YUANDL.R;
Import Com.kejiang.yuandl.utils.ImageSizeUtil;
/** * Custom Round Avatar * Created by Dylan on 2015/11/26 0026. * * public class Circleimageview extends ImageView {/** * circular avatar Default, center_crop!= system default center_crop; * Zoom the picture and so on, so that the long edge of the image and the Imagev
Iew with the same side length, short edges enough to leave blank, zoom after the circular section to display.
* Private static final scaletype Scale_type = Scaletype.center_crop; /** * Image Compression Quality * Alpha_8 is Alpha is composed of 8 bits,------Alpha_8 represents 8-bit alpha bitmap * argb_4444 is composed of 4 4-bit 16-bit,------argb_4444 represents 16-bitARGB Bitmap * argb_8888 is composed of 4 8-bit, namely 32-bit,------argb_8888 represents 32-bit ARGB bitmap * rgb_565 is R 5, G is 6, B is 5 bit 16,------argb_565 represents 8-bit RGB bitmap * * *
private static final Bitmap.config bitmap_config = Bitmap.Config.ARGB_8888;
/** * Default colordrawable width/height/private static final int colordrawable_dimension = 1;
/** * Default Border Width * * private static final int default_border_width = 0;
/** * Default Border color * * private static final int default_border_color = Color.Black;
/** * Picture of the rectangle * * Private final RECTF mdrawablerect = new RECTF ();
/** * Draw the border rectangle * * Private final RECTF mborderrect = new RECTF ();
/** * The matrix to scale and move the picture * * Private final matrix Mshadermatrix = new Matrix ();
/** * Painting pictures of the brush/private final Paint mbitmappaint = new Paint ();
/** * Draw the border of the brush/private final Paint mborderpaint = new Paint ();
/** * Default Border color * * Private int mbordercolor = Default_border_color;
/** * Default Border Width * * private int mborderwidth = Default_border_width;
Private Bitmap Mbitmap;
/** * Produces a picture of a bitmap renderer (Shader)/private Bitmapshader Mbitmapshader; /** * The actual width of the picture * * Private inT Mbitmapwidth;
/** * Picture Actual height * * private int mbitmapheight;
/** * Picture radius * * Private float Mdrawableradius;
/** * Border radius * * Private float Mborderradius;
/** * Initialization Ready * * Private Boolean Mready;
/** * inside margin * * Private Boolean msetuppending; 
Public Circleimageview {Super (context);} public Circleimageview (context, AttributeSet attrs) {
This is (context, attrs, 0); Public Circleimageview (context, AttributeSet attrs, int defstyle) {Super (context, attrs, defstyle); SUPER.SETSC
Aletype (Scale_type); /** * Get the attributes declared in XML/TypedArray a = Context.obtainstyledattributes (Attrs, R.styleable.circleimageview, Defstyle, 0);
Gets the attributes in the XML mborderwidth = A.getdimensionpixelsize (R.styleable.circleimageview_border_width, DEFAULT_BORDER_WIDTH);
Mbordercolor = A.getcolor (R.styleable.circleimageview_border_color, Default_border_color);
A.recycle ();
Mready = true;
if (msetuppending) {setup (); msetuppending = false;}} @Override public ScaleType Getscaletype () {return scale_type;} @OvErride protected void OnDraw (Canvas Canvas) {if (getdrawable () = null) {return;}/** * Draw a circular picture/canvas.drawcircle (GETW
Idth ()/2, GetHeight ()/2, Mdrawableradius, mbitmappaint);
/** * Draw Round border * * * * canvas.drawcircle (GetWidth ()/2, GetHeight ()/2, Mborderradius, mborderpaint); @Override protected void onsizechanged (int w, int h, int oldw, int oldh) {super.onsizechanged (W, H, OLDW, OLDH); Setup (
);
/** * Get Border color * * @return/public int getbordercolor () {return mbordercolor;}/** * Set border color * * @param bordercolor * * public void setBorderColor (int bordercolor) {if (bordercolor = = Mbordercolor) {return;} Mbordercolor = BorderColor; mBo
Rderpaint.setcolor (Mbordercolor);
Invalidate ();
/** * Get Border Width * * @return/public int getborderwidth () {return mborderwidth;}/** * Set Border Width * * @param borderwidth * * public void setborderwidth (int borderwidth) {if (BorderWidth = = mborderwidth) {return;} mborderwidth = BorderWidth; set
Up (); /** * Set Resource picture * * @param BM/@Override public voidSetimagebitmap (Bitmap BM) {Super.setimagebitmap (BM); mbitmap = BM; setup ();/** * Set Resource picture * * @param drawable/@Overri De public void setimagedrawable (drawable drawable) {super.setimagedrawable (drawable); mbitmap = Getbitmapfromdrawable (
drawable);
Setup (); /** * Set Resource ID * * @param resid * * @Override public void Setimageresource (int resid) {super.setimageresource (resid); mBit
Map = getbitmapfromdrawable (getdrawable ());
Setup (); /** * Get Resources Picture * * @param drawable * @return/private Bitmap getbitmapfromdrawable (drawable drawable) {if (drawable = = NULL) {return null;} if (drawable instanceof bitmapdrawable) {return ((bitmapdrawable) drawable). Getbitmap ();} try {B
Itmap bitmap; if (drawable instanceof colordrawable) {bitmap = Bitmap.createbitmap (Colordrawable_dimension, colordrawable_dimension
, bitmap_config); else {imagesizeutil.imagesize ImageSize = imagesizeutil.getimageviewsize (this); bitmap = Bitmap.createbitmap (
ImageSize.Width, Imagesize.height, bitmap_config); } Canvas canvas = new canvas (bitmap);
Drawable.setbounds (0, 0, canvas.getwidth (), Canvas.getheight ());
Drawable.draw (canvas);
return bitmap;
catch (OutOfMemoryError e) {return null;}} /** * The method of drawing circular graphs * * private void Setup () {if (!mready) {msetuppending = true; return;} if (mbitmap = = null) {return;}/*
* * Call this method to produce a renderer (Shader) with a bitmap painted. Bitmap the bitmap used within the renderer Tilex the tiling mode for x to draw the bitmap in. x Direction tile mode Tiley The tiling mode for y to draw the B
Itmap in. The Y-direction tile mode Tilemode: (a total of three kinds) Clamp: If the renderer exceeds the original bounds, it will replicate the range of the edge staining.
REPEAT: Horizontal and vertical repeating renderer picture, tiled.
MIRROR: Horizontal and vertical repeating renderer picture, which is not the same as the repeat repetition, he is tiled in a mirrored way.
* * Mbitmapshader = new Bitmapshader (Mbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
/** * Set Draw round brush/Mbitmappaint.setantialias (TRUE);//Set anti-aliasing Mbitmappaint.setshader (Mbitmapshader);//Graphic transform when drawing graphics
Mborderpaint.setstyle (Paint.Style.STROKE);
Mborderpaint.setantialias (TRUE);
Mborderpaint.setcolor (Mbordercolor);
Mborderpaint.setstrokewidth (Mborderwidth); Mbitmapheight = Mbitmap.getheight ();
Mbitmapwidth = Mbitmap.getwidth ();
/** * Set the coordinates of the bounding rectangle * * Mborderrect.set (0, 0, getwidth (), getheight ()); /** * Set the radius of the bounding rectangle to the maximum of half the width and height of the picture/Mborderradius = Math.max ((mborderrect.height ()-mborderwidth)/2, (mborderrect.width
()-Mborderwidth)/2); /** * Set the coordinates of the picture rectangle * * Mdrawablerect.set (Mborderwidth, Mborderwidth, Mborderrect.width ()-Mborderwidth, Mborderrect.height
()-mborderwidth);
/** * Set the radius of the picture circle to the maximum of half of the width and height of the picture * * * Mdrawableradius = Math.max (Mdrawablerect.height ()/2, Mdrawablerect.width ()/2);
Updateshadermatrix ();
/** * calls the OnDraw () method for painting/invalidate (); /** * Update bitmap rendering/private void Updateshadermatrix () {float scale; float dx = 0; float dy = 0;/** * Reset * * MSHADERMATRIX.S
ET (NULL);
/** * Calculates the scaling ratio, because if the picture is larger than the screen, it will automatically match the size of the screen to display. * Determine the moved XY (*/IF) (Mbitmapwidth * mdrawablerect.height () > Mdrawablerect.width () * mbitmapheight) {scale = Mdrawable
Rect.width ()/(float) mbitmapwidth;
DY = (mdrawablerect.height ()-mbitmapheight * scale) * 0.5f; else {scale = mdrawablerect.heIght ()/(float) mbitmapheight;
DX = (mdrawablerect.width ()-mbitmapwidth * scale) * 0.5f;
} mshadermatrix.setscale (scale, scale);
Mshadermatrix.posttranslate ((int) (dx + 0.5f) + mborderwidth, (int) (dy + 0.5f) + mborderwidth);
/** * Set the local matrix of shader/Mbitmapshader.setlocalmatrix (Mshadermatrix); }
}

2. The Imagesizeutil

used inside

public class Imagesizeutil {/** * is properly compressed according to ImageView * * @param imageview * @return/public static imagesize Getim
Ageviewsize (ImageView imageview) {imagesize imagesize = new ImageSize ();
Displaymetrics displaymetrics = Imageview.getcontext (). Getresources (). Getdisplaymetrics ();
Layoutparams LP = Imageview.getlayoutparams (); int width = imageview.getwidth ()///Gets the actual width of the ImageView if (height <= 0) {if (lp!=null) {width = lp.width;//gets imageview in lay The width declared in out is {<= 0) {//width = Imageview.getmaxwidth ()/check Maximum width = getimageviewfieldvalue (ImageView, "M
MaxWidth "); } if (width <= 0) {width = displaymetrics.widthpixels} int height = imageview.getheight ();//Get the actual height of the ImageView if (he ight <= 0) {if (lp!=null) {height = lp.height;//gets ImageView declared width in layout} if (height <= 0) {height = Getimagevie Wfieldvalue (ImageView, "mmaxheight")/Check Maximum} if (height <= 0) {height = displaymetrics.heightpixels;} imagesize.wi
DTH = width;
Imagesize.height = height; RetUrn ImageSize; public static class ImageSize {public int width, public int height;}}

Usage

Layout file

<com.bulemobi.yuandl.view.circleimageview
android:id= "@+id/ci"
android:layout_width= "180DP
" android:layout_height= "180DP"
android:scaletype= "Centercrop"
android:layout_gravity= "center_horizontal "
app:border_width=" 1DP "
app:border_color=" "#FF0000"
/>

The code in the activity, loading the picture with XUTILS3

Circleimageview circleimageview= (Circleimageview) Findviewbyid (R.ID.CI);
X.image (). Bind (Circleimageview,url,new imageoptions.builder (). Setimagescaletype (ImageView.ScaleType.CENTER_CROP ). Build ()

The above is a small set to introduce the Android custom round avatar Circleimageview support load network Image Implementation code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.