转载请注明出处王亟亟的大牛之路
Android中使用图形处理引擎,2D部分是android SDK内部自己提供,3D部分是用Open GL ES 1.0。
今天写的是关于2D图像的一些简单使用。
图形处理来说,我们最常用到的就是在一个View上画一些图片、形状或者自定义的文本内容,这里我们都是使用Canvas来实现的。你可以获取View中的Canvas对象,绘制一些自定义形状,然后调用View. invalidate方法让View重新刷新,然后绘制一个新的形状,这样达到2D动画效果。下面我们就主要来了解下Canvas的使用方法。
先上效果图。
public class MainActivity extends ActionBarActivity {
LinearLayout imageViewLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageViewLayout=(LinearLayout)findViewById(R.id.imageViewLayout);
imageViewLayout.addView(new customview(this));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/*自定义view*/
class customview extends View {
/*画笔*/
Paint paint;
public customview(Context context) {
super(context);
//设置一个笔刷大小是3的黄色的画笔
paint=new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(3);
}
//在这里我们将测试canvas提供的绘制图形方法
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
}
上面这段代码会让你的页面什么都没有因为在onDraw()方法里并没有给我们的自定义视图做任何绘画的操作,需要重写下onDraw()方法如下
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
效果如下图:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制弧线区域
RectF rect = new RectF(0, 0, 200, 200);
canvas.drawArc(rect, //弧线所使用的矩形区域大小
0, //开始角度
90, //扫过的角度
false, //是否使用中心
paint);
//效果图就不贴了,跟最上面黄色的图一样
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//四分之一圆
canvas.drawArc(rect, //弧线所使用的矩形区域大小
0, //开始角度
90, //扫过的角度
true, //是否使用中心
paint);
}
效果如图
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.BLUE); //整个布局变成蓝色
}
@Override
protected void onDraw(Canvas canvas) {
//定义一个矩形区域
RectF oval = new RectF(0,0,200,300);//矩形区域内切椭圆
canvas.drawOval(oval, paint);
}
@Override
protected void onDraw(Canvas canvas) {
RectF recat = new RectF(50, 50, 200, 200);
//画方块
canvas.drawRect(recat, paint);
}
@Override
protected void onDraw(Canvas canvas) {
RectF rect = new RectF(50, 50, 200, 200);
//方块带圆角
canvas.drawRoundRect(rect,
30, //x轴的半径
30, //y轴的半径
paint);
}
@Override
protected void onDraw(Canvas canvas) {
Path path = new Path(); //定义一条路径
path.moveTo(10, 10); //移动到 坐标10,10
path.lineTo(50, 60);
path.lineTo(200,80);
path.lineTo(10, 10);
//画三角
canvas.drawPath(path, paint);
}
楼主只是简单的举些例子,更多内容一看 android的Canvas.class的源码
代码例子下载地址
访问密码 8fd9