android自定义View绘制几何图形

1、MainActivity.class类

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.graphics.Path;

类实现

public class MainActivity extends Activity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(new GeometryView(this));
	}
	
	//	自定义View
	class GeometryView extends View {
		private Paint paint;
		
		public GeometryView(Context context) {
			super(context);
			
			paint = new Paint();
		}
		
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			
			//	设置背景色
			canvas.drawColor(Color.WHITE);
			
			//	绘制一条线
			paint.setColor(Color.BLACK);
			paint.setStrokeWidth(5);
			canvas.drawLine(0,0,100,100,paint);
			
			//	绘制一个矩形
			paint.setColor(Color.YELLOW);
			canvas.drawRect(0,120,100,200, paint);
			
			//	绘制一个圆
			paint.setColor(Color.BLUE);
			canvas.drawCircle(380, 130, 50, paint);
			
			//	绘制一个椭圆
			paint.setColor(Color.CYAN);
			canvas.drawOval(new RectF(300,370,120,100), paint);
			
			//	绘制一个多边形
			paint.setColor(Color.BLACK);
			Path path = new Path();
			path.moveTo(100, 380);
			path.lineTo(100+45, 380);
			path.lineTo(100+30, 380+50);
			path.lineTo(100+15, 380+50);
			path.close();
			canvas.drawPath(path, paint);
		}
	}	
}

2、效果图

android自定义View绘制几何图形_第1张图片

你可能感兴趣的:(Android)