Matrix is called a matrix in Chinese. It is introduced in advanced mathematics. In terms of image processing, it is mainly used for operations such as plane scaling, translation, and rotation.
First, we will introduce matrix operations. Addition and subtraction are not required. It is too simple to add the corresponding bits. Image processing mainly uses multiplication. The following is a multiplication formula:
In Android, matrix is a 3*3 matrix consisting of 9 float values. For example.
Without professional tools, the painting is ugly. The SiNx and cosx above indicate the COs and sin values of the rotation angle. Note that the rotation angle is calculated clockwise. Translatex and translatey indicate the translation quantity of X and Y. Scale is the scale ratio, 1 is the same, 2 is the scale 1/2, this way.
Next, we will try the effect of matrix on Android.
Java Code
-
- Public class myview extends view {
-
- Private bitmap mbitmap;
- Private matrix mmatrix = new matrix ();
-
- Public myview (context ){
-
- Super (context );
-
- Initialize ();
-
- }
-
- Private void initialize (){
-
- Mbitmap = (bitmapdrawable) getresources (). getdrawable (R. drawable. Show). getbitmap ();
-
- Float cosvalue = (float) math. Cos (-math. PI/6 );
-
- Float sinvalue = (float) math. Sin (-math. PI/6 );
- Mmatrix. setvalues (
-
- New float [] {
-
- Cosvalue,-sinvalue, 100,
-
- Sinvalue, cosvalue, 100,
-
- 0, 0, 2 });
-
- }
-
- @ Override protected void ondraw (canvas ){
- // Super. ondraw (canvas); // Of course, if there are other elements to draw on the interface, just write this sentence.
-
- Canvas. drawbitmap (mbitmap, mmatrix, null );
-
- }
-
- }
Public class myview extends view {private bitmap mbitmap; private matrix mmatrix = new matrix (); Public myview (context) {super (context); initialize ();} private void initialize () {mbitmap = (bitmapdrawable) getresources (). getdrawable (R. drawable. show )). getbitmap (); float cosvalue = (float) math. cos (-math. PI/6); float sinvalue = (float) math. sin (-math. PI/6); mmatrix. setvalues (new float [] {cosvalue,-S Invalue, 100, sinvalue, cosvalue, 0, 0, 2}) ;}@ override protected void ondraw (canvas) {// super. ondraw (canvas); // Of course, if there are other elements to be drawn on the interface, just write this sentence. Canvas. drawbitmap (mbitmap, mmatrix, null );}}
The running result is as follows:
Take the top left corner as the vertex, zoom in half, rotate 30 degrees counter-clockwise, and then translate 50 pixels along the X axis and Y axis, respectively. The Code writes 100. Why translate 50, because it is scaled in half.
You can set the value of matrix by yourself, or try to multiply the two matrices to set the value so that you can be more familiar with matrix.
The direct assignment method mentioned here may be a bit difficult to understand, but fortunately, andrid provides a more convenient method for the matrix, which will be introduced in the next article.