Package Com.example.coustomviewdemo;import Android. R.interpolator;import Android.content.context;import Android.graphics.canvas;import Android.graphics.Color;import Android.graphics.paint;import Android.graphics.paint.fontmetrics;import Android.util.attributeset;import Android.view.view;public class Fightviewdemo extends View {public Fightviewdemo (context context) {super (context);// TODO auto-generated Constructor Stubinit (context,null);} Public Fightviewdemo (context context, AttributeSet Attrs) {Super (context, attrs);//TODO Auto-generated constructor Stubinit (context, attrs);} Public Fightviewdemo (context context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);//TODO Auto-generated constructor Stubinit (context, attrs);} Private Paint paint;private void init (context context, AttributeSet attrs) {Paint = new Paint ();p Aint.setcolor (color.red) ;} @Overrideprotected void OnDraw (canvas canvas) {//TODO auto-generated method Stubsuper.ondraw (canvas);//todo drawing text//WholeA parent control getheight int height = getheight ();//The entire parent control getwidthint width = getwidth ();//How can I get the height and width of the component itself? String Text = "Lovehelloworld"; FontMetrics metrics = Paint.getfontmetrics (); int descent = (int) metrics.descent;//initializes the size of the character that widths the length of text. Float[] widths = new Float[text.length ()];//Gets the pixel width of each character in a brother string. Paint.gettextwidths (text, widths);//Gets the length of its own component int mywidth=0;for (int i=0;i<widths.length;i++) {Mywidth+=widths[i] ;} Gets the height of its own component int th = (int) paint.gettextsize (); int posX = (width-mywidth)/2;int PosY = height/2 + TH/2-descent;//session own text content: C Anvas.drawtext (text, PosX, PosY, paint);//Standard Linecanvas.drawline (0, HEIGHT/2, width, HEIGHT/2, paint); Canvas.drawline ( WIDTH/2, 0, WIDTH/2, height, paint);}}
Android---------Custom View