canvse的save和restore方法总结

    xiaoxiao2021-03-25  28

    概要:

    save:用来保存Canvas的状态。save之后,可以调用Canvas的平移、放缩、旋转、错切、裁剪等操作。

    restore:用来恢复Canvas之前保存的状态。防止save后对Canvas执行的操作对后续的绘制有影响。

    saverestore要配对使用(restore可以比save少,但不能多),如果restore调用次数比save多,会引发Error

    直接上代码和截图,看代码注释

    package com.example.drawtest; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class MyTextView extends View { public MyTextView(Context context) { super(context); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); } public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint bluePaint = getPaint(Color.BLUE, Paint.Style.FILL); Paint redPaint = getPaint(Color.RED, Paint.Style.FILL); Paint whitePaint = getPaint(Color.WHITE, Paint.Style.FILL); Paint cyanPaint = getPaint(Color.CYAN, Paint.Style.STROKE); Paint blackPaint = getPaint(Color.BLACK, Paint.Style.STROKE); //绘制蓝色底图和一个红色圆圈 draw(canvas, bluePaint, redPaint); //保存当前状态 canvas.save(); //顺时针旋转15 canvas.rotate(15); //在旋转后的画布上绘制一个黑色矩形边框和红色圆圈 draw(canvas, blackPaint, redPaint); //再进行缩放一半操作 canvas.scale(0.5f, 0.5f); //绘制一个浅蓝色边框和红色圆圈后将图像缩放一半 draw(canvas, cyanPaint, redPaint); //恢复之前保存的状态 canvas.restore(); //在之前的画布上继续绘制一个白色圆圈,相对前一个圆圈右移 canvas.drawCircle(getMeasuredWidth() * 8 / 10, 20, 20, whitePaint); } /** * @param canvas 画布 * @param rectPaint 矩形用到的画笔 * @param circlePaint 圆形用到的画笔 */ private void draw(Canvas canvas, Paint rectPaint, Paint circlePaint) { canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), rectPaint); canvas.drawCircle(getMeasuredWidth() * 7 / 10, 20, 20, circlePaint); } /** * 获取画笔 * * @param color 画笔颜色 * @param style 画笔风格 * @return 画笔 */ public Paint getPaint(int color, Paint.Style style) { Paint paint = new Paint(); paint.setStrokeWidth(20); paint.setAntiAlias(true); paint.setStyle(style); paint.setColor(color); return paint; } }

    <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.drawtest.MainActivity"> <com.example.drawtest.MyTextView android:layout_width="300dp" android:layout_height="500dp" android:layout_centerInParent="true"/> </RelativeLayout>

    运行效果图

    其实他的实现逻辑,如下图所示

    注意点:移动或者旋转后,坐标仍然是按照之前的坐标来计算

    转载请注明原文地址: https://ju.6miu.com/read-50356.html

    最新回复(0)