Android Open Source series: Circleimageview Customizing the use of circular controls

Source: Internet
Author: User

1. Customizing circular controls GitHub Address:Https://github.com/hdodenhof/CircleImageView

The main classes:

Package De.hdodenhof.circleimageview;import Edu.njupt.zhb.main.r;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;public Class    Circleimageview extends ImageView {private static final scaletype Scale_type = Scaletype.center_crop;    private static final Bitmap.config bitmap_config = Bitmap.Config.ARGB_8888;    private static final int colordrawable_dimension = 1;    private static final int default_border_width = 0;    private static final int default_border_color = Color.Black; Private final RECTF Mdrawablerect = nEW RECTF ();    Private final RECTF mborderrect = new RECTF ();    Private final Matrix Mshadermatrix = new Matrix ();    Private final paint Mbitmappaint = new paint ();    Private final paint Mborderpaint = new paint ();    private int mbordercolor = Default_border_color;    private int mborderwidth = Default_border_width;    Private Bitmap Mbitmap;    Private Bitmapshader Mbitmapshader;    private int mbitmapwidth;    private int mbitmapheight;    private float Mdrawableradius;    private float Mborderradius;    Private Boolean Mready;    Private Boolean msetuppending;    Public Circleimageview (Context context) {super (context);    } public Circleimageview (context context, AttributeSet Attrs) {This (context, attrs, 0);        } public Circleimageview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);        Super.setscaletype (Scale_type); TypedArray a = Context.obtainstyledattributes (Attrs, R.styleable.circleimageview, DefSTyle, 0);        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 public void Setscaletype (ScaleType scaletype) {if (ScaleType! = scale_type) {throw n        EW IllegalArgumentException (String.Format ("ScaleType%s not supported.", ScaleType));        }} @Override protected void OnDraw (canvas canvas) {if (getdrawable () = = null) {return;        } canvas.drawcircle (GetWidth ()/2, GetHeight ()/2, Mdrawableradius, mbitmappaint);    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 ();    } public int Getbordercolor () {return mbordercolor;        } public void setBorderColor (int bordercolor) {if (bordercolor = = Mbordercolor) {return;        } Mbordercolor = bordercolor;        Mborderpaint.setcolor (Mbordercolor);    Invalidate ();    } public int Getborderwidth () {return mborderwidth;        } public void Setborderwidth (int borderWidth) {if (borderWidth = = mborderwidth) {return;        } mborderwidth = BorderWidth;    Setup ();        } @Override public void Setimagebitmap (Bitmap bm) {Super.setimagebitmap (BM);        Mbitmap = BM;    Setup ();        } @Override public void setimagedrawable (drawable drawable) {super.setimagedrawable (drawable);        Mbitmap = getbitmapfromdrawable (drawable);    Setup (); } @Override public void Setimageresource (int resId) {Super.setimageresource (resId);        Mbitmap = Getbitmapfromdrawable (getdrawable ());    Setup ();        } private Bitmap getbitmapfromdrawable (drawable drawable) {if (drawable = = null) {return null;        } if (drawable instanceof bitmapdrawable) {return ((bitmapdrawable) drawable). Getbitmap ();            } try {Bitmap Bitmap; if (drawable instanceof colordrawable) {bitmap = Bitmap.createbitmap (Colordrawable_dimension, COLORDRAWABL            E_dimension, Bitmap_config); } else {bitmap = Bitmap.createbitmap (Drawable.getintrinsicwidth (), Drawable.getintrinsicheight (), Bitmap_c            Onfig);            Canvas canvas = new canvas (bitmap);            Drawable.setbounds (0, 0, canvas.getwidth (), Canvas.getheight ());            Drawable.draw (canvas);        return bitmap;        } catch (OutOfMemoryError e) {return null; }} private void Setup (){if (!mready) {msetuppending = true;        Return        } if (Mbitmap = = null) {return;        } Mbitmapshader = new Bitmapshader (Mbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);        Mbitmappaint.setantialias (TRUE);        Mbitmappaint.setshader (Mbitmapshader);        Mborderpaint.setstyle (Paint.Style.STROKE);        Mborderpaint.setantialias (TRUE);        Mborderpaint.setcolor (Mbordercolor);        Mborderpaint.setstrokewidth (Mborderwidth);        Mbitmapheight = Mbitmap.getheight ();        Mbitmapwidth = Mbitmap.getwidth ();        Mborderrect.set (0, 0, getwidth (), getheight ());        Mborderradius = Math.min ((mborderrect.height ()-mborderwidth)/2, (Mborderrect.width ()-mborderwidth)/2); Mdrawablerect.set (Mborderwidth, Mborderwidth, Mborderrect.width ()-Mborderwidth, Mborderrect.height ()-MBorderWidth        );        Mdrawableradius = Math.min (Mdrawablerect.height ()/2, Mdrawablerect.width ()/2); UpdateshAdermatrix ();    Invalidate ();        } private void Updateshadermatrix () {float scale;        float dx = 0;        float dy = 0;        Mshadermatrix.set (NULL); if (Mbitmapwidth * mdrawablerect.height () > Mdrawablerect.width () * mbitmapheight) {scale = MDrawableRect.h            Eight ()/(float) mbitmapheight;        DX = (mdrawablerect.width ()-mbitmapwidth * scale) * 0.5f;            } else {scale = Mdrawablerect.width ()/(float) mbitmapwidth;        DY = (mdrawablerect.height ()-mbitmapheight * scale) * 0.5f;        } mshadermatrix.setscale (scale, scale);        Mshadermatrix.posttranslate ((int) (dx + 0.5f) + mborderwidth, (int) (dy + 0.5f) + mborderwidth);    Mbitmapshader.setlocalmatrix (Mshadermatrix); }}

Custom properties: Res/values/attrs.xml

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Circleimageview" >        <attr name= "Border_width" format= "Dimension"/>        <attr name= "border_color" format= "Color"/>    </declare-styleable></resources>

Layout file when used:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "xmlns:app=" Http://schemas.android.com/apk/res-auto "android:layout_width=" Match_parent "Android:layout_h eight= "match_parent" android:orientation= "vertical" > <relativelayout android:layout_width= "Match_paren        T "android:layout_height=" 0DP "android:layout_weight=" 1 "android:padding=" @dimen/base_padding " android:background= "@color/light" > <de.hdodenhof.circleimageview.circleimageview android:layout_w Idth= "160DP" android:layout_height= "160DP" android:layout_centerinparent= "true" android:s rc= "@drawable/demo" app:border_width= "2DP" app:border_color= "@color/dark"/> </relativelayo ut> <relativelayout android:layout_width= "match_parent" android:layout_height= "0DP" Android: layout_weight= "1" android:padding= "@dimen/base_padding" android:background= "@color/dark" > <de.hdodenhof.circleimageview.circleimag Eview android:layout_width= "160DP" android:layout_height= "160DP" Android:layout_centerinp Arent= "true" android:src= "@drawable/lena" app:border_width= "2DP" app:border_color= "@color /light "/> </RelativeLayout></LinearLayout>

Effect:



Demo Download: http://download.csdn.net/detail/nuptboyzhb/7284553


Note: Some developers may also find that if we need a round imagebutton, in fact, we do not need to write it ourselves. If the ImageButton icon is fixed, we can let the designer design a round picture for me, and then set it directly on the ImageButton. However, please note that our circular imageview here is a custom control, that is: no matter what picture you set, the display is round. For example: Easy to trust the user's avatar settings, regardless of what the user took photos, show is a round.

Expand reading :

There is also a more powerful roundedimageview, which also supports rounded corners, ellipses, and so on.

Https://github.com/vinc3m1/RoundedImageView


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.