自定義組件---圖片和文字實現ImageButton效果

一、效果圖java

二、自定義代碼:canvas

<span style="font-family:Comic Sans MS;font-size:14px;">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();
	}
	/**
	 * 初始化數據
	 */
	private void init() {
		displayMetrics = getDisplayMetrics();
		mImagePaint = new Paint();
		mTextPaint = new Paint();
		mTextPaint.setColor(Color.BLACK);
		mTextPaint.setTextSize(mTextSize*displayMetrics.density);
//		
		mTextPaint.setAntiAlias(true); // 打開抗矩齒  
		imageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.home); 
		//設置背景顏色
		setBackground(getResources().getDrawable(R.drawable.item_background_selector));
		//設置點擊事件
		setOnClickListener(this);
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		viewHeight = getHeight();
		imageTop = (viewHeight - imageBitmap.getHeight())/2;
		//是文字在垂直方向上居中
		textTop = (int) ((viewHeight - getFontHeight(mTextPaint))/2-mTextPaint.getFontMetrics().top);
	}
	
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawBitmap(imageBitmap, 10, imageTop, mImagePaint);
		canvas.drawText("打開",imageBitmap.getWidth()+20, textTop, mTextPaint);
	}
	
	
	/**
	 * 獲取手機分辨率
	 * @return
	 */
	public DisplayMetrics getDisplayMetrics() {   
        DisplayMetrics dm = new DisplayMetrics();   
        //取得DisplayMetrics對象方法一  
        dm = context.getApplicationContext().getResources().getDisplayMetrics();   
        //取得DisplayMetrics對象方法二  
//      ((Activity)cx).getWindowManager().getDefaultDisplay().getMetrics(dm);  
        return dm;   
     } 
	
	/**
	 * 獲取字體的高度
	 * @param paint
	 * @return
	 */
	private int getFontHeight(Paint paint){
		FontMetrics fm = paint.getFontMetrics();
		return (int)Math.ceil(fm.descent - fm.ascent);  
	}

	/**
	 * 改變字體顏色
	 */
	@Override
	public 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);
	}
	
	@Override
	public void onClick(View v) {
		 
	}
	 
}</span>

三、文字居中參考

http://blog.csdn.net/hursing/article/details/18703599
ide

相關文章
相關標籤/搜索