Android自定義控件之自定義View(二)

轉載請註明出處:http://blog.csdn.net/xiaohao0724/article/details/54375779


通過上一篇的學習相信我們已經對自定義控件有了一定程度的瞭解,本篇我們將實現點擊屏幕時以點擊的這個點爲圓心畫圓並放大的效果。

效果如下圖:



1、自定義RingView繼承View添加其構造方法並創建畫筆

public class RingView extends View {


 private static final String TAG = "Havorld";
	/**
	 * 圓心的X座標
	 */
	private float cx;
	/**
	 * 圓心的Y座標
	 */
	private float cy;
	/**
	 * 圓環半徑
	 */
	private float radius;
	/**
	 * 默認畫筆
	 */
	private Paint paint;
	private int[] colors = new int[] { Color.BLUE, Color.RED, Color.YELLOW,
			Color.GREEN, Color.DKGRAY };
	protected boolean isRunning = false;

	public RingView(Context context) {
		this(context, null);
	}

	public RingView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public RingView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initView();
	}

	private void initView() {

		radius = 0;
		paint = new Paint();
		paint.setAntiAlias(true);
		paint.setStyle(Style.STROKE); // 空心圓
		paint.setStrokeWidth(radius / 4); // 畫筆寬度 半徑4分之一
		paint.setColor(colors[(int) (Math.random() * 5)]); // 畫筆顏色
		paint.setAlpha(255); // 不透明
	}
}


2、通過Handler遞歸調用onDraw畫圓

private Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
 
			// 設置透明度
			int alpha = paint.getAlpha();
			if (alpha == 0) {
				isRunning = false;
			}
 
			// 透明度每次-10, 慢慢變透明
			alpha = Math.max(0, alpha - 10);

			paint.setAlpha(alpha);

			// 設置半徑
			radius += 5; // 半徑越來越大
			paint.setStrokeWidth(radius / 3);

			invalidate();

			if (isRunning) {
				handler.sendEmptyMessageDelayed(0, 50); // 繼續遞歸調用
			}

		};
	};

	
	
	/**
	 * 執行動畫
	 */
	private void startAnim() {
		isRunning = true;
		handler.sendEmptyMessageDelayed(0, 100);
	}


	// 銷燬View的時候調用
	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		isRunning = false;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		
		canvas.drawCircle(cx, cy, radius, paint);
	}

3、通過複寫onTouchEvent方法處理按下事件確定圓心

        @Override
	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);

		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			cx = event.getX();
			cy = event.getY();
			initView();
			startAnim();

		}
		return true;

	}

點擊下載源碼


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章