[android自定義控件]之繪圖

        作者:sundroid

       個人站點:sundroid.cn    郵箱: [email protected]   微博:http://weibo.com/Sundroid

本文編碼(utf-8)http://download.csdn.net/detail/hfut11/7899653

效果圖   



自定義View CustomView繼承View,重寫父類onDraw函數。

package com.sundroid.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class CustomView extends View {
	// 圖形類型
	int type = 0;
	// 重寫父類onDraw函數
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		Paint paint = new Paint();
		paint.setColor(Color.GREEN);
		paint.setStrokeWidth(10);
		switch (type) {
		// 畫圓形
		case 0:
			canvas.drawCircle(200, 200, 100, paint);
			break;
		// 畫矩形
		case 1:
			canvas.drawRect(60, 90, 360, 100, paint);
			break;
		// 三角形
		case 2:
			Path path = new Path();
			path.moveTo(80, 100);
			path.lineTo(420, 250);
			path.lineTo(80, 350);
			path.close();
			canvas.drawPath(path, paint);
			break;

		default:
			break;
		}

	}

	public void changeType() {
		type++;
		if (type > 2) {
			type = 0;
		}
	}

	// 構造函數
	public CustomView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

}
 

package com.sundroid.customview;

import com.sundroid.widget.CustomView;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {
	private CustomView customView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		customView = (CustomView) findViewById(R.id.custView);
		customView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Message message = new Message();
				message.what = 1;
				myHandler.sendMessage(message);
			}
		});
	}

	Handler myHandler = new Handler() {
		// 接收到消息後處理
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				customView.changeType();
				customView.invalidate();

				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

}


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