• 使用android画布的save()和restore()方法


    在调用画布的save()方法之后,可以对画布进行平移、旋转等操作,

    然后再将需要画的内容draw到画布上去,

    最后再调用restore()方法,恢复到调用save()方法之前的状态。

    1 public class SubView extends TextView { 2 3 public SubView(Context context, AttributeSet attrs) { 4 super(context, attrs); 5 } 6 7 protected void onDraw(android.graphics.Canvas canvas) { 8 int px = getMeasuredWidth(); 9 int py = getMeasuredHeight(); 10 11 Paint backgroundPaint = new Paint(); 12 backgroundPaint.setColor(Color.CYAN); 13 canvas.drawRect(0, 0, px, py, backgroundPaint); 14 15 canvas.save(); 16 // 顺时针旋转180度 17 canvas.rotate(180, px / 2, py / 2); 18 19 Paint linePaint = new Paint(); 20 linePaint.setColor(Color.RED); 21 22 canvas.drawLine(px / 2, 0, 0, py / 2, linePaint); 23 canvas.drawLine(px / 2, 0, px, py / 2, linePaint); 24 canvas.drawLine(px / 2, 0, px / 2, py, linePaint); 25 26 // 恢复到调用save()方法之前的状态 27 // 即没有顺时针旋转180度 28 canvas.restore(); 29 30 canvas.drawCircle(px - 20, py - 20, 20, linePaint); 31 }; 32 }

    在这个例子中,调用save()方法之后,将画布进行顺时针旋转了180度,画了三条线段,

    然后调用restore()方法恢复到顺时针旋转180度之前,再画一个实心圆。

    布局文件内容:

    1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" > 5 6 <com.example.test.SubView 7 android:layout_margin="20dip" 8 android:layout_width="fill_parent" 9 android:layout_height="fill_parent" 10 android:layout_centerHorizontal="true" 11 android:layout_centerVertical="true" 12 tools:context=".MainActivity" /> 13 14 </RelativeLayout>

    程序运行之后的屏幕截图:

    image

  • 相关阅读:
    关于此主题 v1
    从博客园主题了解前端 CSS
    VS2019 许可证到期
    从博客园主题了解前端 HTML
    关于此主题
    从博客园主题了解前端 JS
    GCC 编译器
    Python的Set和List的性能比较 + 两者之间的转换
    wsgi初探(转)
    权限设计概要
  • 原文地址:https://www.cnblogs.com/fengzhblog/p/3088538.html
Copyright © 2020-2023  润新知