解释
Canvas的save()、restore()这两个方法字面意思就是保存、恢复,但为什么要保存和回复呢?不保存会怎么样?
如上图当使用 canvas.translate(50,50)方法后canvas的坐标中心就不是左上角,而是(50,50),如图左边数第一个黑色直角就是 第一次canvas.translate(50,50)后的坐标中心。我用了一个for循环对同一个canvas(注意是同一个canvas)
执行了5次canvas.translate(50,50),从图中发现canvas每次都以当前坐标中心为基础移动(50,50),如上图。但是如果遇到在for循环中对canvas执行translate后不想canvas改变坐标中心怎么办?那就在canvas translate前save,后再restore。如下注释代码。
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
* Creator: Jowney (~._.~)
* Date: 2019/3/22/0:43
* Description:
*/
public class MainTest extends Activity {
private static final String TAG = "MainTest";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static class MyView extends View{
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < 5; i++) {
//canvas.save()
Path path = new Path();
path.lineTo(100,0);
path.moveTo(0,0);
path.lineTo(0,100);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
canvas.translate(50,50);
canvas.drawPath(path,paint);
//canvas.restore()
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
tools:context=".MainActivity">
<view
class="jowney.com.animationtest.MainTest$MyView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent" />
</LinearLayout>