Android Custom View Advanced-matrix principle

Source: Internet
Author: User

Matrix principle author Weibo: @GcsSloop "related articles in this series" Preface

This article is biased in theory, and the canvas operation has overlapping parts, this article will give you a deeper understanding of the principles.

The protagonist matrix of this article is a model worker who has been working silently in the background, although we all see the matrix behind the view of the credit, but we seldom see it, this article we will see where it is sacred.

As Google has already done a good job of packaging this part, so skip this part of the actual development impact is not too large, do not want to delve into the rough view, the next article will be detailed on the matrix of the specific usage and skills.

Matrix Introduction

Matrices are a matrix, the main function is coordinate mapping, numerical conversion.

It might look like this:

Matrix is a coordinate mapping, so why do you need a matrix? To give a simple example:

My phone screen as a physical device, its physical coordinate system starts from the upper left corner, but we usually do not use this coordinate system at the time of development, but instead use the coordinate system of the content area.

For example, our content area and screen coordinate system also differ from one notification bar and a title bar distance, so the two are not coincident, we in the content area in the coordinate system of the final drawing of the content must be converted to the actual physical coordinate system to draw, the role of the matrix here is to convert these values.

>
Assuming that the notification bar is 20 pixels tall and the navigation bar height is 40 pixels, we draw a point at the (0,0) position in the content area and eventually convert to a point in the actual coordinate system (0,60).

The above is only as a simple example, in fact, whether 2D or 3D, we want to display graphics on the screen, can not be separated from the matrix, so that the matrix is a hard work in the back of the workers.

Matrix Features
    • Wider scope, matrix in the view, pictures, animation effects and other aspects of the use, compared with the previous explanation and other canvas operation wider application.

    • More flexible, the canvas operation is the package of the Matrix, the matrix as a closer to the bottom of things, must be more flexible than the canvas operation.

    • The package is good, the matrix itself is a good package for each method, so that developers can easily operate the matrix.

    • Difficult to understand deeply, it is difficult to understand the meaning of the various values, as well as the rules of operation, if you do not understand the matrix, it is difficult to understand the previous multiplication.

Common misconceptions

1. It is considered that the three parameters (Mpersp_0, mpersp_1, mpersp_2) of the Matrix's bottom line are not much of a function here, just for the sake of dine.

In fact, the last row of parameters plays a critical role in the 3D transformation, which is described in detail in the following camera article.

2. The last parameter mpersp_2 is interpreted as scale

It is true that changing the value of mpersp_2 can achieve a scale-like effect, but this is because of the homogeneous coordinates, not the actual function of this parameter.

Matrix Fundamentals

Matrix, the most fundamental function of which is the transformation of coordinates, let's look at the principles of several common transformations:

All of the transformations we use are affine transformations, which are the composite of linear transformations (scaling, rotation, tangent) and translational (translational), since these concepts are not very useful to us, but they are more interesting to understand.

There are 4 basic transformations: panning (translate), scaling (scale), rotation (rotate), and error-cutting (skew).

Let's take a look at the parameters that are controlled by each of the four transformations.


From the last three parameters can be seen to control the perspective, these three parameters are mainly used in the 3D effect, usually (0, 0, 1), not in the scope of this discussion, not too much to describe, will later in the article detailed its role.

Since most of our calculations are based on matrix multiplication rules, if you have returned the linear algebra to the teacher, please refer to here:
Wikipedia-matrix multiplication

1. Scaling (Scale)

Represented by a matrix:

You may have noticed that we have a 1 more coordinates, which is the reason for using the homogeneous coordinate system, in mathematics our points and vectors are represented in this way (x, y), the two look the same, the computer cannot differentiate, for this reason the computer can also differentiate them, add a flag bit, and then it looks like this:

(x, Y, 1)-point

(x, y, 0)-Vector

In addition, homogeneous coordinates have the properties of equal ratio, (2,3,1), (4,6,2) ... (2n,3n,n) represents the point (2,3). (The misconception that mpersp_2 is interpreted as scale stems from this ).

Legend:

2. Wrong Cut (Skew)

There are two kinds of special error cut, horizontal error cutting (parallel x axis) and vertical error cutting (parallel y axis).

Horizontal Error Cutting

Represented by a matrix:

Legend:

Vertical Error Cutting

Represented by a matrix:

Legend:

Compound Error Cutting

A combination of horizontal and vertical dislocation.

Represented by a matrix:

Legend:

3. Rotation (Rotate)

Assume a point a (x0, y0), the distance from the origin is r, the angle of the horizontal axis is α, the θ is rotated around the origin, and the rotation is point B (x, y) as follows:

Represented by a matrix:

Legend:

4. Pan (Translate)

Here is one of the advantages of using homogeneous coordinates, in fact, the previous three operations using a 2x2 matrix can also meet the requirements, but using a 2x2 matrix, the translation operation can not be added to it, and the coordinates are expanded to the sub-coordinates, the matrix can be extended to 3x3 to unify the algorithm, Each of the four algorithms can be completed using matrix multiplication.

Represented by a matrix:

Legend:

Matrix Composite principle

In fact, many of the matrix of composite operations are implemented using matrix multiplication, the principle of understanding is very simple, but the use of matrix multiplication also has its weaknesses, the subsequent operations may affect the front to the operation, so in the construction of the Matrix when the order is very important.

We used four major transformations, each operation in the matrix has three categories, the pre-multiply (pre), post-multiply (post) and set (set), you can see at the end of the matrix method table, because matrix multiplication does not meet the Exchange law, so the pre-multiply (pre), post-multiply (post) and set (set) The difference is still very big.

Pre-multiply (pre)

The forward multiplication is the right multiplication of the matrix:

This represents a matrix with a special matrix before the multiplication of the result matrix.

Back Multiply (POST)

The front multiplication is the same as the left multiply of the matrix:

This represents a matrix with a special matrix followed by multiply after the result matrix is constructed.

Setting (SET)

Instead of using matrix multiplication, the setting overrides the original value directly, so the use of the setting may result in the previous operation being invalidated .

Combination

The ultimate goal of our use of the matrix is to make the view appear as we want it to be, and for that we may need a combination of actions.

I've found a lot of articles that explain the matrix like to use an example of scaling (rotating) around a certain point, as follows:

那么我们如果想让它基于图片中心缩放,应该该怎么办?要用到组合变换,  1)先将图片由中心平移到原点,这是应用变换 T  2)对图应用缩放变换 S   3)再将图片平移回到中心,应用变换 -T对应代码:  matrix.postScale(0.5f, 0.5f);    matrix.preTranslate(-pivotX, -pivotY);    matrix.postTranslate(pivotX, pivotY);  PS: 此段文字引用自其它文章。

First of all, this idea is not any problem, but also to achieve around a certain point of operation of the core principle , but this may be a part of the small white cause misunderstanding, think that can only be achieved, but look at the matrix method table can know the four operations can specify the center point, so, The above three lines of code can be done in one line:

matrix.postScale(0.50.5f, pivotX, pivotY);

Composite operation when constructing the matrix, the individual recommends as far as possible to use the whole after or all of the use of pre-multiplication, so that the sequence of operations is easy to determine, there are problems are easier to troubleshoot.
Of course, since the matrix multiplication does not satisfy the commutative law, the results of the pre-multiplication and the post-multiplication are different and should be used in combination with the specific scenario analysis.

The difference between pre and post

The main difference is that the multiplication order of the matrix is different, the pre is equivalent to the right multiplication of the matrix, and the post is equivalent to the left multiplication of the matrix.

The following views are ambiguous, so do delete annotations:


In image processing, the closer to the right of the matrix executes first, so the pre operation executes first, and the post operation executes.

In practice, we get accurate results for every step of the operation, but why do we have to use a sequential argument? Is it really possible to use pre and post to influence the order of calculations? In fact, we use an example to illustrate the following:

new Matrix();matrix.postScale(0.50.8f);matrix.preTranslate(10001000"MatrixTest:3" + matrix.toShortString());

In the above operation, if the normal way of thinking, the first scaling, after panning, the scaling operation before the execution, will not affect the subsequent panning operation, but the execution results found that the translation distance into (500, 800).

In the above example, the calculation order is no problem, the calculation of the scale, and then the translation of the calculation, and the scaling effect to the translation is because the result matrix of the previous step is scaled to the right by the translation matrix, which is consistent with the matrix multiplication of the Operation law, that is, the scaling operation has affected the translation operation, This is equivalent to performing a panning operation and then performing a scaling operation, so that the pre operation is performed first, and the post operation executes this statement .

Here we construct a matrix in different ways:

Let's say we need to zoom and pan first.

Attention:

    • 1. Since matrix multiplication does not satisfy the commutative law, ensure that the initial matrix (Initial matrix) is used, otherwise it may result in a different operation.
    • 2. Note the construction order, which can affect the result.
    • The 3.Initial matrix refers to the new matrix, or the matrix after reset, which is a unit matrix.
1. Use the Pre only:
new//使用pre,越靠后越先执行。m.preScale(sx, sy);

Represented by a matrix:

2. Use post only:
new Matrix();m.reset();m.postScale(sx, sy);  //使用post,越靠前越先执行。m.postTranslate(tx, ty);

Represented by a matrix:

3. Mixing:
new Matrix();m.reset();m.preScale(sx, sy);  m.postTranslate(tx, ty);

Or:

new Matrix();m.reset();m.postTranslate(tx, ty);m.preScale(sx, sy);  

Because there are only two steps here, and the order is specified successively, the exchange on the code does not affect the result.

Represented by a matrix:

Note: Since matrix multiplication does not satisfy the commutative law, ensure that the initial matrix is empty and that the initial matrix is not empty, resulting in a different result of the operation.

Matrix Method Table

This method table, temporarily put here to let everyone see, the method of using the explanation in the next article.

Method Category related APIs Summary
Basic methods equals Hashcode toString toshortstring Compare, get hashes, convert to strings
Numeric operations Set Reset Setvalues getValues Set, reset, set a value, get a value
Numerical calculation Mappoints Mapradius Maprect mapvectors Calculate the value after transformation
Setting (SET) Setconcat setRotate Setscale Setskew settranslate Setting transformations
Pre-multiply (pre) Preconcat prerotate Prescale Preskew pretranslate Forward multiplication transformation
Back Multiply (POST) Postconcat postrotate Postscale Postskew posttranslate Post-Multiply transformations
Special methods Setpolytopoly Setrecttorect Rectstaysrect Setsincos Some special operations
Matrix-related Invert Isaffine isidentity To find the inverse matrix, whether it is an affine matrix, whether it is a unit matrix ...
Summarize

For the matrix to understand and understand the principles behind it will be more handy to use.

After finishing this article, we recommend to cooperate with Hon Yang Big Video Course
Create a personalized picture preview and multi-touch consumption, which will allow you to understand the matrix to a higher level.

About Me author Micro-blog: @GcsSloop

Resources

Matrix

The principle, code verification and application of Image transform matrix in Android

Some understandings on the pre-multiplication of matrix in Android

Wikipedia-Affine transformations

Wikipedia-Homogeneous coordinates

Wikipedia-linear mapping

The entry-level thinking of homogeneous coordinate system

Affine transformation and homogeneous coordinates


Android Custom View Advanced-matrix principle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.