[android自定义控件]之绘图

        作者:sundroid

       个人站点:sundroid.cn    邮箱: hfutsnjc@163.com   微博: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);
		}
	};

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值