android 之 画图

Matrix以顺时针旋转为正,这一点与三角函数里面的角度定义刚好相反。

先说几个常用的方法:setValues()以及set、pre、post系列的方法,如果当前矩阵是A变化矩阵是B则pre表示A * B,post表示B * A关于此的详细介绍可以参考http://zensheno.blog.51cto.com/2712776/513652http://philn.blog.163.com/blog/static/104014753201351795246382/

初次给矩阵setValues的时候要注意,如以下代码:

img = (ImageView)findViewById(R.id.matrix_test);
float[] x = {1,0,300, // 如果不对图片做旋转操作那么前两个数保持1,0
			 0,1,300, // 同上,保持0,1;对于旋转来说 1表示对应的x,y不变及不旋转
			 0,0,1};
Matrix matrix = new Matrix();
matrix.setValues(x);
Bitmap sourceImg = BitmapFactory.decodeResource(getResources(), R.drawable.temp);
Bitmap resizedBitmap = Bitmap.createBitmap(sourceImg, 0, 0,
		sourceImg.getWidth(), sourceImg.getHeight(), matrix, true);
//		img.setImageBitmap(resizedBitmap);
BitmapDrawable myNewBitmapDrawable = new BitmapDrawable(resizedBitmap);
img.setImageDrawable(myNewBitmapDrawable);
注意以上注释部分,如果把1换为0则会出报异常;

android的基本图形接口:

1.Bitmap,可以来自资源/文件,也可以在程序中创建,实际上的功能相当于图片的存储空间(可以理解为“内存中的虚拟画布”);

2.Canvas,紧密与Bitmap联系,把Bitmap比喻内容的话,那么Canvas就是提供了众多方法操作Bitamp的平台(相对于Bitmap是实际的画布);

3.Paint,与Canvas紧密联系,是"画板"上的笔刷工具,也用于设置View控件上的样式; 

4.Drawable,Drawable就是把前三者绘图结果表现出来的接口。Drawable多个子类,例如:位图(BitmapDrawable)、图形(ShapeDrawable)、图层(LayerDrawable)等。


下面通过几端代码说明下以上的作用:

public class TestView extends View {
private ShapeDrawable mDrawable;
public testView(Context context) {
super(context);
int x = 10;
int y = 10;
int width = 300;
int height = 50;
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas)
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);//View的白色背景
mDrawable.draw(canvas);
}
}
自定义的View;

Bitmap bmp=BitmapFactory.decodeResource(r, R.drawable.icon);//只读,不能直接在bmp上画  
Bitmap newb = Bitmap.createBitmap( 300, 300, Config.ARGB_8888 );  
  
Canvas canvasTemp = new Canvas( newb );  
canvasTemp.drawColor(Color.TRANSPARENT);  
  
Paint p = new Paint();  
String familyName ="宋体";  
Typeface font = Typeface.create(familyName,Typeface.BOLD);  
p.setColor(Color.RED);  
p.setTypeface(font);  
p.setTextSize(22);  
canvasTemp.drawText("写字。。。",50,50,p);  
canvasTemp.drawBitmap(bmp, 50, 50, p);//画图  
imageView.setImageBitmap(newb); 
把ImageView的图片设置为通过Canvas绘制的图;



发布了21 篇原创文章 · 获赞 6 · 访问量 5万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章