教你如何用Android画一个几何图形

教你如何用Android画一个几何图形
2012-06-22 19:11:55|分类: Android|标签:绘制集合图形|字号大中小 订阅
先来介绍一下画几何图形要用到的,画布(Canvas)、画笔(Paint)。
1. 画一个圆使用的是drawCircle:canvas.drawCircle(cx, cy, radius, paint); x、y代表坐标、radius是半径、paint是画笔,就是画图的颜色;
2. 在画图的时候还要有注意,你所画的矩形是实心(paint.setStyle(Paint.Style.FILL))还是空心(paint.setStyle(Paint.Style.STROKE);
画图的时候还有一点,那就是消除锯齿:paint.setAntiAlias(true);
3. 还有就是设置一种渐变颜色的矩形:
Shader mShader = new LinearGradient(0,0,100,100, new int[]{Color.RED,Color.GREEn,Color.BLUE,Color.YELLO},null,Shader.TileMode.REPEAT);
ShapeDrawable sd;
//画一个实心正方形
sd = new ShapeDrawable(new RectShape());
sd.setBounds(20,20,100,100);
sd.draw(canvas);
//一个渐变色的正方形就完成了

4. 正方形:drawRect:canvas.drawRect(left, top, right, bottom, paint)
这里的left、top、right、bottom的值是:
left:是矩形距离左边的X轴
top:是矩形距离上边的Y轴
right:是矩形距离右边的X轴
bottom:是矩形距离下边的Y轴
5. 长方形:他和正方形是一个原理,这个就不用说了
6. 椭圆形:记住,这里的Rectf是float类型的
RectF re = new Rect(left, top, right, bottom);
canvas.drawOval(re,paint);
【教你如何用Android画一个几何图形】
好了,说了这么多的的东西,那就让我们来看一下真正的实例吧!!!
package com.hades.game;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
public class CanvasActivity extends Activity {
/**
* 画一个几何图形
* hades
*蓝色着衣
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyView myView = new MyView(this);
setContentView(myView);
}
public class MyView extends View {
public MyView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 设置画布的背景颜色
canvas.drawColor(Color.WHITE);
/**
* 定义矩形为空心
*/
// 定义画笔1
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
// 消除锯齿
paint.setAntiAlias(true);
// 设置画笔的颜色
paint.setColor(Color.RED);
// 设置paint的外框宽度
paint.setStrokeWidth(2);
// 画一个圆
canvas.drawCircle(40, 30, 20, paint);
// 画一个正放形
canvas.drawRect(20, 70, 70, 120, paint);
// 画一个长方形
canvas.drawRect(20, 170, 90, 130, paint);
// 画一个椭圆
RectF re = new RectF(20, 230, 100, 190);
canvas.drawOval(re, paint);
/**
* 定义矩形为实心
*/
paint.setStyle(Paint.Style.FILL);
// 定义画笔2
Paint paint2 = new Paint();
// 消除锯齿
paint2.setAntiAlias(true);
// 设置画笔的颜色
paint2.setColor(Color.BLUE);
// 画一个空心圆
canvas.drawCircle(150, 30, 20, paint2);
// 画一个正方形
canvas.drawRect(185, 70, 130, 120, paint2);
// 画一个长方形
canvas.drawRect(200, 130, 130, 180, paint2);
// 画一个椭圆形
RectF re2 = new RectF(200, 230, 130, 190);
canvas.drawOval(re2, paint2);
}
}
}
运行效果如下:

    推荐阅读