前言
Matrix 就是矩阵的意思,我们通常使用它进行一些图片的变化操作
平移、缩放、旋转、错切、水印等效果
矩阵
{
0,0,1
1,0,0
1,0,0
}
{
MSCALE_X MSKEW_X MTRANS_X
MSKEW_Y MSCALE_Y MTRANS_Y
MPERSP_0 MPERSP_1 MPERSP_2
}
常用api
Matrix 三种动作 pre 、post 、set
pre代表之前有操作,乖乖排队
post代表插队到第一个
set代表设置,替换之前所有
平移Translate
通过改变矩阵 MTRANS_X、MTRANS_Y
preTranslate(float dx,float dy)
postTranslate(float dx,float dy)
setTranslate(float dx,float dy)
private void translate() {
mMatrix.reset();
mMatrix.preTranslate(100, 100);
invalidate();
}
旋转 Rotate
通过 MSCALE_X、MSKEW_X、MSCALE_Y、MSKEW_Y
preRotate(float degrees)
preRotate(float degrees, float dx,float dy)
...
private void rotate() {
mMatrix.reset();
mMatrix.preRotate(180, bitmap.getWidth() / 2f, bitmap.getHeight() / 2f);
invalidate();
}
缩放Scale
通过矩阵 MSCALE_X、MSCALE_Y
preRotate(float dx,float,dy)
...
private void scale() {
mMatrix.reset();
mMatrix.preScale(2, 2, bitmap.getWidth() / 2f, bitmap.getHeight() / 2f);
invalidate();
}
扭曲变幻 Skew
点(x,y)通过Skew(dx,dy,px,py)变幻之后的坐标 kx(y-py)+px , ky(x-px)+py
preSkew(float kx,float ky)
preSkew(float kx,float ky,float px,float,py)
...
private void skew() {
mMatrix.reset();
mMatrix.preSkew(1, 0, bitmap.getWidth() / 2f, bitmap.getHeight() / 2f);
invalidate();
}
水印效果
private Bitmap addStamp(Bitmap bottomBitmap) {
Bitmap bitmap = Bitmap.createBitmap(bottomBitmap.getWidth(), bottomBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(bottomBitmap, 0, 0, mPaint);
//绘制矩形
mPaint.setColor(Color.parseColor("#55CCCCCC"));
RectF rectF = new RectF(0, bitmap.getHeight() - 80, bitmap.getWidth(), bitmap.getHeight());
canvas.drawRect(rectF, mPaint);
//绘制文字
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(20);
mPaint.setColor(Color.parseColor("#666666"));
canvas.drawText("多多最帅", bitmap.getWidth() / 2f, bitmap.getHeight() - 80 / 2f + 20/2f , mPaint);
return bitmap;
}