Android uses ImageView to make transparent arc instance code _android

Source: Internet
Author: User
Tags getcolor

These days because of the requirements of the project, you need to overlay a layer of transparent arc on the ImageView, and in the direction of the arc to display the corresponding text, the effect as shown in the following figure:


To get this requirement, the first thing to think of is customizing a imageview to implement this function, that is, to draw arcs and text in OnDraw (). At the same time because to ensure that the position of the arc can be arbitrarily placed, the arc color, transparency and text size, color, etc. are controllable, so added some custom attributes. The implementation code is very simple, as follows:

1. Custom ImageView:

Package Com.chunk.customviewsdemo.views.ArcImageView;
Import Android.content.Context;
Import Android.content.res.TypedArray;
Import Android.graphics.Canvas;
Import Android.graphics.Paint;
Import Android.graphics.Path;
Import Android.graphics.RectF;
Import Android.util.AttributeSet;
Import Android.widget.ImageView;
Import COM.CHUNK.CUSTOMVIEWSDEMO.R;  /** * DESCRIPTION:A Custom ImageView with circular arc and text * Author:xiaoyu * Date://: */public class Arcimageview Extends ImageView {/** * The default text size. * * Private final float default_text_size =/** * The default scale Val
UE which decides the width of arc.
* Private final float Default_scale =. F;
/** * The default transparency of arc.
* Private final int default_arc_alpha =;
/** * The default width of arc.
* Private final int default_arc_width =;
/** * The default angle the arc starts with.
* Private final int default_start_angle =;
/** * The default angle that arc. * Private Final int Default_sweep_anGLE =;
/** * The default distance along the path to add to the text ' starting position.
* Private final int default_h_offset =;
/** * The default distance above (-) or below (+) the path to position the text.
* Private final int default_v_offset =;
Private context Mcontext;
/** * The text displayed on ImageView along arc.
* * Private String mdrawstr;
/** * The font size of text.
* Private float mtextsize = default_text_size;
/** * The scale value which decides the width of arc.
* Private float Mscale = Default_scale;
/** * The transparency of arc.
* * Private int marcalpha = Default_arc_alpha;
/** * The width of arc.
* * Private int marcwidth = Default_arc_width;
/** * The start angle of angle.
* * Private int mstartangle = Default_start_angle;
/** * The swept angle of angle.
* * Private int msweepangle = Default_sweep_angle;
/** * The default distance along the path to add to the text ' starting position.
* Private float mhoffset = Default_h_offset; /** * The default distance above (-) or below (+) the path to position the text.
* Private float mvoffset = Default_v_offset;
/** * The style of arc, all styles includes Left_top, Left_bottom, Right_top, Right_bottom, CENTER.
* Of course, can add your own style according to your demands.
* * private int mdrawstyle;
/** * The color of arc.
* * private int marccolor;
/** * The color of text.
* * private int mtextcolor; Public Arcimageview (context) {super (context); this.mcontext = context;} public Arcimageview (context, ATT  Ributeset attrs) {Super (context, attrs); this.mcontext = context; obtainattributes (attrs);} public Arcimageview (context Context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr); this.mcontext = context; obtainattr
Ibutes (ATTRS);
}/** * Set The text that is drawn on arc.
* @param drawstr the text content. */public void Setdrawstr (String drawstr) {this.mdrawstr = Drawstr;//refresh this view invalidate ();}/** * Set the TRA
Nsparency of Arc. * @paramMarcalpha the value of transparency. */public void Setarcalpha (int marcalpha) {this.marcalpha = Marcalpha;//refresh this view invalidate ();} @Override Prot ected void OnDraw (Canvas Canvas) {Super.ondraw (Canvas);//draw arc Paint arcpaint = new Paint (); Arcpaint.setstrokewidth (
Marcwidth);
Arcpaint.setstyle (Paint.Style.STROKE);
Arcpaint.setcolor (Marccolor);
Arcpaint.setalpha (Marcalpha);
int width = getwidth ();
int height = getheight ();
float radius;
if (width > height) {radius = Mscale * height;} else {radius = Mscale * WIDTH;}
RECTF Oval = new RECTF ();
int center_x = width;
int center_y = height; Switch (mdrawstyle) {case:center_x =; center_y =; Mstartangle =; msweepangle =-; break; case:center_x =; Center_
y = height;
Mstartangle =;
Msweepangle =;
Break
case:center_x = width;
Center_y =;
Mstartangle =;
Msweepangle =-;
Break
case:center_x = width;
center_y = height;
Mstartangle =;
Msweepangle =;
Break
case:center_x = width/;
center_y = height/; MsTartangle =;
Msweepangle =;
Break
float left = Center_x-radius;
float top = Center_y-radius;
float right = center_x + radius;
Float Bottom = center_y + radius;
Oval.set (left, top, right, bottom);
Canvas.drawarc (oval, Mstartangle, Msweepangle, False, Arcpaint);
Draw text Paint textpaint = new Paint ();
Textpaint.settextsize (mtextsize);
Textpaint.setstyle (Paint.Style.FILL);
Textpaint.setcolor (Mtextcolor);
Path PATH = new Path ();
Path.addarc (oval, Mstartangle, msweepangle);
Canvas.drawtextonpath (mdrawstr, Path, Mhoffset, Mvoffset, Textpaint);
}/** * Obtain custom attributes that been defined in Attrs.xml.
* @param attrs A Collection of attributes. * * private void Obtainattributes (AttributeSet attrs) {TypedArray ta = mcontext.obtainstyledattributes (Attrs,
R.styleable.arcimageview);
Mdrawstr = ta.getstring (R.STYLEABLE.ARCIMAGEVIEW_DRAWSTR);
Mtextsize = Ta.getdimension (r.styleable.arcimageview_textsize, default_text_size); Marcalpha = Ta.getinteger (R.styleable.arcimageview_arcalpHa, Default_arc_alpha);
Marcwidth = Ta.getinteger (R.styleable.arcimageview_arcwidth, default_arc_width);
Mstartangle = Ta.getinteger (R.styleable.arcimageview_startangle, Default_start_angle);
Msweepangle = Ta.getinteger (R.styleable.arcimageview_startangle, Default_sweep_angle);
Mhoffset = Ta.getinteger (R.styleable.arcimageview_hoffset, Default_h_offset);
Mvoffset = Ta.getinteger (R.styleable.arcimageview_voffset, Default_v_offset);
Marccolor = Ta.getcolor (R.styleable.arcimageview_arccolor, XCCCCCC);
Mtextcolor = Ta.getcolor (R.styleable.arcimageview_textcolor, XFFFFFF);
Mdrawstyle = Ta.getint (R.styleable.arcimageview_drawstyle,);
Ta.recycle (); }
}

2. Custom properties in Attrs.xml under the Values folder:

 <?xml version=". "Encoding=" utf-"?> <resources> <declare-styleable Name= "Arcimageview" > <attr name= "drawstr" format= "string"/> <attr the Name= "Textsize" format= "Dimension"/ > <attr name= "arcalpha" format= "integer"/> <attr name= "arcwidth" format= "integer"/> <attr "name=" StartAngle "format=" integer "/> <attr name=" sweepangle "format=" integer "/> <attr name=" scale "format=" Float "/> <attr name=" hoffset "format=" float "/> <attr name=" voffset "format=" float "/>" <attr name= "dra Wstyle "format=" enum "> <enum name=" left_top "value=" "/>" <enum name= "Left_bottom" value= ""/> <enum Nam E= "Right_top" value= "/> <enum name=" Right_bottom "value=" "/> <enum name=" CENTER "value=" "/> </attr&
Gt <attr name= "Arccolor" format= "color"/> <attr name= "textcolor" format= "Color"/> </declare-styleable > </resources> 

3. Call Arcimageview in Mainactivity, implementing the Code as follows:

Package Com.chunk.customviewsdemo;
Import Android.os.Bundle;
Import android.support.v.app.appcompatactivity;
Import Android.view.View;
Import Android.widget.Button;
Import Com.chunk.customviewsdemo.views.ArcImageView.ArcImageView; public class Mainactivity extends Appcompatactivity implements View.onclicklistener {private Arcimageview aiv_one; priva
Te Arcimageview aiv_two;
Private Arcimageview Aiv_three;
Private Arcimageview Aiv_four;
Private Button Btn_another_one;
private int mgroup =; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
Aiv_one = (Arcimageview) Findviewbyid (R.id.aiv_one);
Aiv_one.setarcalpha ();
Aiv_two = (Arcimageview) Findviewbyid (r.id.aiv_two);
Aiv_two.setarcalpha ();
Aiv_three = (Arcimageview) Findviewbyid (R.id.aiv_three);
Aiv_three.setarcalpha ();
Aiv_four = (Arcimageview) Findviewbyid (R.id.aiv_four);
Aiv_four.setarcalpha (); Btn_another_one = (Button) Findviewbyid (R.id.btn_anoTher_one);
Btn_another_one.setonclicklistener (this); @Override public void OnClick (View v) {switch (V.getid ()) {case R.id.btn_another_one:if (mgroup = =) {Aiv_one.setdra
WSTR ("Apple");
Aiv_one.setbackgroundresource (r.drawable.apple);
Aiv_two.setdrawstr ("Pomelo");
Aiv_two.setbackgroundresource (r.drawable.pineapple);
Aiv_three.setdrawstr ("banana");
Aiv_three.setbackgroundresource (R.drawable.banana);
Aiv_four.setdrawstr ("pineapple");
Aiv_four.setbackgroundresource (r.drawable.pineapple);
Mgroup =; else {aiv_one.setdrawstr ("steak"); Aiv_one.setbackgroundresource (R.drawable.steak); Aiv_two.setdrawstr ("Seafood"); aiv_
Two.setbackgroundresource (R.drawable.seafood);
AIV_THREE.SETDRAWSTR ("cheese");
Aiv_three.setbackgroundresource (R.drawable.cheese);
Aiv_four.setdrawstr ("barbecue");
Aiv_four.setbackgroundresource (r.drawable.barbecue);
Mgroup =;
} break; }
}
}

The layout file for

4.MainActivity is as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:custom= "http://
Schemas.android.com/apk/res-auto "android:layout_width=" match_parent "android:layout_height=" Match_parent "
Android:layout_margintop= "DP" android:layout_marginbottom= "DP" android:orientation= "vertical" > <button
Android:id= "@+id/btn_another_one" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "swap"/> <linearlayout android:layout_width= "match_parent" android:layout_height= "DP" Android: Layout_weight= "" "android:orientation=" Horizontal "> <relativelayout android:layout_width=" DP "Android:layout_
weight= "" android:layout_height= "Match_parent" > <com.chunk.customviewsdemo.views.arcimageview.arcimageview Android:id= "@+id/aiv_one" android:layout_width= "match_parent" android:layout_height= "Match_parent" Android: background= "@drawable/steak" custom:drawstyle= "Right_bottom" custom:drawstr= "Steak" custom:arcalpha= "" Custom: Arccolor= "@color/gray"
Custom:textcolor= "@color/black" custom:textsize= "sp"/> </RelativeLayout> <relativelayout android: Layout_width= "DP" android:layout_weight= "" android:layout_height= "Match_parent" > < Com.chunk.customviewsdemo.views.ArcImageView.ArcImageView android:id= "@+id/aiv_two" android:layout_width= "Match_ Parent "android:layout_height=" match_parent "android:background=" @drawable/seafood "custom:drawstyle=" LEFT_BOTTOM "Custom:drawstr=" Seafood "custom:arcalpha=" "custom:arccolor=" @color/gray "custom:textcolor=" @color/black "Custom: textsize= "sp"/> </RelativeLayout> </LinearLayout> <linearlayout android:layout_width= "Match_ Parent "android:layout_height=" DP "android:layout_weight=" "android:orientation=" Horizontal "> < Relativelayout android:layout_width= "DP" android:layout_weight= "" android:layout_height= "Match_parent" > < Com.chunk.customviewsdemo.views.ArcImageView.ArcImageView android:id= "@+id/aiv_three" android:layout_width= " Match_parent "Android:layout_height= "Match_parent" android:background= "@drawable/cheese" custom:drawstyle= "right_top" custom:drawstr= "Cheese" Custom: Arcalpha= "" Custom:arccolor= @color/gray "custom:textcolor= @color/black" custom:textsize= "sp"/> </ Relativelayout> <relativelayout android:layout_width= "DP" android:layout_weight= "android:layout_height="
Match_parent "> <com.chunk.customviewsdemo.views.arcimageview.arcimageview android:id=" @+id/aiv_four "
Android:layout_width= "Match_parent" android:layout_height= "match_parent" android:background= "@drawable/barbecue" Custom:drawstyle= "left_top" custom:drawstr= "barbecue" custom:arcalpha= "custom:arccolor=" @color/gray "custom:textColor=" "@color/black" custom:textsize= "sp"/> </RelativeLayout> </LinearLayout> </LinearLayout>

Note that when you introduce custom attributes into a layout file, you need to add one line of code: xmlns:custom= "Http://schemas.android.com/apk/res-auto".

Well, the need is done, and the rest is to move to the actual project. The implementation effect is as follows:


To sum up, custom view is generally used to rewrite OnDraw, Onmeasure (), OnLayout () and other methods to measure, draw, the general use of the canvas, Paint, bitmap and other classes, The process of measurement and drawing is actually the abstraction and realization of the drawing work in the real life, we use the object-oriented thought to the Sketchpad, drawing paper, brush and other tools and painting action with a line of code to describe the OK!

Because the implementation process is relatively simple, I do not paste the source code, if you are not very familiar with the 2D drawing, you can go to search the relevant information or read related books!

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.