android学习7——canvas.concat(Matrix matrix)作用
canvas.concat的作用可以理解成对matrix的变换应用到canvas上的所有对象.
看下面的代码.
public class ConcatMatrixActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new ConcatMatrixView(this));
}
}
public class ConcatMatrixView extends View {
private Matrix matrix = new Matrix();
private Paint bgPaint = new Paint();
public ConcatMatrixView(Context context) {
super(context);
matrix.setScale(2f, 2f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
bgPaint.setColor(Color.RED);
canvas.drawRect(0, 0, 100, 100, bgPaint);
canvas.save();
canvas.concat(matrix);
canvas.drawRect(100, 100, 200, 200, bgPaint);
canvas.restore();
canvas.drawRect(400, 400, 500, 500, bgPaint);
}
}
以上代码对matrix的x和y坐标都拉伸了2倍.变化的效果如下所示:
在没有concat的情况下canvas.drawRect(100, 100, 200, 200, bgPaint);是在(100, 100), (200, 200)的区域下画一个矩形.因为执行了matrix.setScale(2f, 2f)所以matrix的x和y坐标都拉伸了2倍.这时候在concat的作用下canvas.drawRect(100, 100, 200, 200, bgPaint)变成了在(200, 200), (400, 400)的区域上画矩形.
同理,如果把对matrix的变换由matrix.setScale(2f, 2f)改成matrix.setTranslate(100f, 100f),效果如下所示:
x轴和y轴坐标都移动了100个像素.
posted on