您的位置:首页 > 其它

【canvas】Canvas的效果操作及save()和restore()方法应用

2014-03-27 15:37 471 查看
http://blog.163.com/gobby_1110/blog/static/29281715201010188417838/

平移、缩放、旋转等操作等于是,我在一个正的画布绘制好图,然后再把画布做旋转、平移、缩放等等的效果。

也就是说,我使用的X、Y坐标还是正常的坐标(没旋转、平移、缩放等之前的坐标)。



save()和restore()是用来规定操作的范围的。

如果有save()和restore(),那么平移、缩放、旋转等操作只对save()和restore()作用域之间的代码有效。

在此我参考了http://www.javaeye.com/topic/440623



然后我做了代码测试(在onDraw()中画图),如下:

protected void onDraw(Canvas canvas){

//首先定义中心点和半径

int px=getMeasuredWidth()/2;

int py=getMeasuredHeight()/2;



int radius=Math.min(px, py);



canvas.drawCircle(px, py, radius, circlePaint);

canvas.save();//注释save①

canvas.rotate(-bearing, px, py);

//canvas.save();



int textWidth=(int)textPaint.measureText("W");

int cardinalX=px-textWidth/2;

int cardinalY=py-radius+textHeight;



//开始绘制刻度和文字

//每15度一个刻度,每45度一个数字,每90度一个方向

for(int i=0; i<24; i++){

canvas.drawLine(px, py-radius, px, py-radius+10, markerPaint);



canvas.save();//注释save②

canvas.translate(0, textHeight);





if(i%6==0){

String dirString="";

switch(i){

case(0):{

dirString=northString;

int arrowY=2*textHeight;

canvas.drawLine(px, arrowY, px-5, 3*textHeight, markerPaint);

canvas.drawLine(px, arrowY, px+5, 3*textHeight, markerPaint);

break;

}

case(6):dirString=eastString;break;

case(12):dirString=westString;break;

case(18):dirString=southString;break;

}

canvas.drawText(dirString, cardinalX, cardinalY, textPaint);

}

else if(i%3==0){

String angle=String.valueOf(i*15);

float angleTextWidth=textPaint.measureText(angle);



int angleX=(int)(px-angleTextWidth/2);

int angleY=py-radius+textHeight;

canvas.drawText(angle, angleX, angleY, textPaint);

}

canvas.restore();//注释restore②

canvas.rotate(15, px, py);



}

//测试save()和restore()的作用域

canvas.drawText("Hello world 在restore之前!", 100, 100, textPaint);

canvas.restore();//注释restore①

canvas.drawText("Hello world 在restore之后!", 100, 100, textPaint);

}

//结论:在save②到restore②之间所画的图顶点下移textHeight个像素,restore②之后的代码不受影响

//在save①到restore①之间所画的内容都选择45°,restore①之后的代码不会旋转

//注意save②到restore②也是在save①到restore①作用之内的,所以save②到restore②之间的内容不但顶点下移textHeight个像素,并且旋转

//45度。




最近开始看英文原版的《Professional Android Application Development》
这本书真的是非常的好 国内的开发书籍看了4本了 和这本书比50%都赶不上
书内很多内容需要再到网上查相关内容 然后才能很清晰的了解
想多学点 再多学点
想自己能在研究生毕业前作到Professional
不是想 是一定要 一定要做到专业
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: