Detailed explanation of Canvas API (Part 3)Matrix and drawBitmapMash


Introduction to this section:

In the Canvas API document, we see such a method: drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint)

This Matrix has a big article. We have talked about ColorMatrix before in the ColorFilter in the Paint API. Color matrix, a 4 * 5 matrix, we can modify the hue, saturation, etc. by modifying the matrix value! The Matrix we are talking about today can be combined with other APIs to control the transformation of graphics and components. For example, Canvas provides the above This drawBitmap is used to achieve the effect of matrix transformation! Let's study this stuff slowly~

Official API document:Matrix


1. Several commonly used transformation methods in Matrix

  • setTranslate(float dx, float dy): Control the Matrix for translation
  • setRotate(float degrees, float px , float py): rotation, the parameters are: rotation angle, axis (x, y)
  • setScale(float sx, float sy, float px, float py): scaling, The parameters are: scaling ratio on the The scaling ratio on the axis
  • is actually basically the same as the Canvas transformation method. After setting the above transformation for the Matrix, call the Canvas The drawBitmap() method just calls the matrix~
2.Matrix usage example:


Running renderings

:

Code implementation1.gif

MyView.java

/**
 * Created by Jay on 2015/11/11 0011.
 */
public class MyView extends View {

    private Bitmap mBitmap;
    private Matrix matrix = new Matrix();
    private float sx = 0.0f;          //设置倾斜度
    private int width,height;         //位图宽高
    private float scale = 1.0f;       //缩放比例
    private int method = 0;

    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void init() {
        mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.img_meizi);
        width = mBitmap.getWidth();
        height = mBitmap.getHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        switch (method){
            case 0:
                matrix.reset();
                break;
            case 1:
                sx += 0.1;
                matrix.setSkew(sx,0);
                break;
            case 2:
                sx -= 0.1;
                matrix.setSkew(sx,0);
                break;
            case 3:
                if(scale  0.5){
                    scale -= 0.1;
                }
                matrix.setScale(scale,scale);
                break;
        }
        //根据原始位图与Matrix创建新图片
        Bitmap bitmap = Bitmap.createBitmap(mBitmap,0,0,width,height,matrix,true);
        canvas.drawBitmap(bitmap,matrix,null);    //绘制新位图
    }

    public void setMethod(int i){
        method = i;
        postInvalidate();
    }
}

Layout code:activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/ly_bar"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:layout_alignParentBottom="true">

        <Button
            android:id="@+id/btn_reset"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="重置" />

        <Button
            android:id="@+id/btn_left"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="左倾" />

        <Button
            android:id="@+id/btn_right"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="右倾" />

        <Button
            android:id="@+id/btn_zoomin"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="放大" />

        <Button
            android:id="@+id/btn_zoomout"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="缩小" />
    </LinearLayout>


    <com.jay.canvasdemo3.MyView
        android:id="@+id/myView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/ly_bar" />

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button btn_reset;
    private Button btn_left;
    private Button btn_right;
    private Button btn_zoomin;
    private Button btn_zoomout;
    private MyView myView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
    }

    private void bindViews() {
        btn_reset = (Button) findViewById(R.id.btn_reset);
        btn_left = (Button) findViewById(R.id.btn_left);
        btn_right = (Button) findViewById(R.id.btn_right);
        btn_zoomin = (Button) findViewById(R.id.btn_zoomin);
        btn_zoomout = (Button) findViewById(R.id.btn_zoomout);
        myView = (MyView) findViewById(R.id.myView);


        btn_reset.setOnClickListener(this);
        btn_left.setOnClickListener(this);
        btn_right.setOnClickListener(this);
        btn_zoomin.setOnClickListener(this);
        btn_zoomout.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_reset:
                myView.setMethod(0);
                break;
            case R.id.btn_left:
                myView.setMethod(1);
                break;
            case R.id.btn_right:
                myView.setMethod(2);
                break;
            case R.id.btn_zoomin:
                myView.setMethod(3);
                break;
            case R.id.btn_zoomout:
                myView.setMethod(4);
                break;
        }
    }
}

The usage is very simple, I won’t explain it~

3.drawBitmapMash distorted image


There is also such a method in the API documentation:

drawBitmapMesh

(Bitmap bitmap, int meshWidth, int meshHeight, float[] verts, int vertOffset, int[] colors, int colorOffset, Paint paint)

The parameters are:

bitmap

: The original bitmap that needs to be distorted

meshWidth/

meshHeight

: Divide the original bitmap into how many grids horizontally/vertically verts: The length is (meshWidth+1) *(meshHeight+2) array, which records each vertex of the distorted bitmap (grid line intersection) Position, although it is a one-dimensional array, the data it actually records is in the format of (x0, y0), (x1, y1).. (xN, Yn), These array elements control the distortion effect on the bitmap bitmap

vertOffset: Control the verts array starting from which array element to distort the bitmap (ignoring the data before verOffset distortion effect)

Code example:

Running renderings:

3.gif

Code implementation

/**
 * Created by Jay on 2015/11/11 0011.
 */
public class MyView extends View {

    //将水平和竖直方向上都划分为20格
    private final int WIDTH = 20;
    private final int HEIGHT = 20;
    private final int COUNT = (WIDTH + 1) * (HEIGHT + 1);  //记录该图片包含21*21个点
    private final float[] verts = new float[COUNT * 2];    //扭曲前21*21个点的坐标
    private final float[] orig = new float[COUNT * 2];    //扭曲后21*21个点的坐标
    private Bitmap mBitmap;
    private float bH,bW;


    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void init() {
        mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.img_wuliao);
        bH = mBitmap.getWidth();
        bW = mBitmap.getHeight();
        int index = 0;
        //初始化orig和verts数组。
        for (int y = 0; y <= HEIGHT; y++)
        {
            float fy = bH * y / HEIGHT;
            for (int x = 0; x <= WIDTH; x++)
            {
                float fx = bW * x / WIDTH;
                orig[index * 2 + 0] = verts[index * 2 + 0] = fx;
                orig[index * 2 + 1] = verts[index * 2 + 1] = fy;
                index += 1;
            }
        }
        //设置背景色
        setBackgroundColor(Color.WHITE);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmapMesh(mBitmap, WIDTH, HEIGHT, verts
                , 0, null, 0, null);
    }

    //工具方法,用于根据触摸事件的位置计算verts数组里各元素的值
    private void warp(float cx, float cy)
    {
        for (int i = 0; i = 1)
            {
                verts[i + 0] = cx;
                verts[i + 1] = cy;
            }
            else
            {
                //控制各顶点向触摸事件发生点偏移
                verts[i + 0] = orig[i + 0] + dx * pull;
                verts[i + 1] = orig[i + 1] + dy * pull;
            }
        }
        //通知View组件重绘
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        //调用warp方法根据触摸屏事件的座标点来扭曲verts数组
        warp(event.getX(), event.getY());
        return true;
    }

}

Implementation process analysis

First of all, you have to figure out what is stored in this verts array? for example verts[0] and verts1, these two adjacent elements actually represent the x-coordinate and y-coordinate of our first point! Knowing this, you know why there are 21 * 21 points, and why the array length is equal to this value * 2! You will understand the initialization part!

Then let’s take a look at the implementation of calculating the value of the verts array element based on touch events: Obtain the x, y coordinates of the touch point, subtract this value from the x, y coordinates of the corresponding point, and calculate the distance between the touch point and each coordinate point. Then calculate the so-called degree of distortion: 80000 / ((float) (dd * d)); if the degree of distortion >= 1, directly let the coordinates If the point points to this touch point, < 1, each vertex will be offset to the touch point, and then invalidate() will be called to redraw~ That's about it~ Think more and think about it. If you still don't understand, forget it. It's good to know that this thing exists!


4. Download the example of this section:

CanvasDemo3.zip

CanvasDemo4.zip


Summary of this section:

Most of the contents of this section are excerpted from Li Gang's "Android" Crazy Lecture Notes, which may be a little easier to understand~ Matrix should be understandable by most children, but drawBitmapMash may take a while to distort the image. Time to digest and digest, it’s okay if you don’t understand~ Well, that’s it for this section, thank you4.gif