Android---------Custom View

Source: Internet
Author: User

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

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.