Custom components-image and text for ImageButton
1,
2. Custom Code:
Public class ImageTextView extends View implements OnClickListener {private Paint mImagePaint; private Paint mTextPaint; private int mTextSize = 16; private Bitmap imageBitmap; private Context context; private int viewHeight; private DisplayMetrics displayMetrics; private int imageTop; private int textTop; public ImageTextView (Context context) {super (context); this. context = context; init ();} public ImageTextView (Context context, AttributeSet attrs) {super (context, attrs); this. context = context; init ();} public ImageTextView (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle); this. context = context; init ();}/*** initialization data */private void init () {displayMetrics = getDisplayMetrics (); mImagePaint = new Paint (); mTextPaint = new Paint (); mTextPaint. setColor (Color. BLACK); mTextPaint. setTextSize (mTextSize * displayMetrics. density); // mTextPaint. setAntiAlias (true); // enable the anti-moment tooth imageBitmap = BitmapFactory. decodeResource (getResources (), R. drawable. home); // set the background color setBackground (getResources (). getDrawable (R. drawable. item_background_selector); // sets the Click Event setOnClickListener (this);} @ Overrideprotected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {super. onMeasure (widthMeasureSpec, heightMeasureSpec); viewHeight = getHeight (); imageTop = (viewHeight-imageBitmap. getHeight ()/2; // The text is centered vertically. textTop = (int) (viewHeight-getFontHeight (mTextPaint)/2-mTextPaint.getFontMetrics (). top) ;}@ Overrideprotected void onDraw (Canvas canvas) {super. onDraw (canvas); canvas. drawBitmap (imageBitmap, 10, imageTop, mImagePaint); canvas. drawText ("open", imageBitmap. getWidth () + 20, textTop, mTextPaint);}/*** get cell phone resolution * @ return */public DisplayMetrics getDisplayMetrics () {DisplayMetrics dm = new DisplayMetrics (); // obtain the DisplayMetrics object method dm = context. getApplicationContext (). getResources (). getDisplayMetrics (); // method 2 for obtaining the DisplayMetrics object // (Activity) cx ). getWindowManager (). getdefadisplay display (). getMetrics (dm); return dm;}/*** get the font height * @ param paint * @ return */private int getFontHeight (Paint paint) {FontMetrics fm = paint. getFontMetrics (); return (int) Math. ceil (fm. descent-fm. ascent);}/*** change font color */@ Overridepublic boolean onTouchEvent (MotionEvent event) {switch (event. getAction () {case MotionEvent. ACTION_DOWN: mTextPaint. setColor (Color. BLUE); break; case MotionEvent. ACTION_UP: mTextPaint. setColor (Color. BLACK); break; default: break;} invalidate (); return super. onTouchEvent (event) ;}@ Overridepublic void onClick (View v ){}}
3. Text Center Reference
Http://blog.csdn.net/hursing/article/details/18703599