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

来源:互联网 发布:youtube视频软件 编辑:程序博客网 时间:2024/06/09 16:20

原文: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度。

0 0
原创粉丝点击