Android Basic Notes (15)-graphics, solving big picture oom, use of painting tools and exercises

Source: Internet
Author: User
Tags gety

    • The principle of computer graphics representation
    • Loading a large image appears oom
    • Zoom load a large picture resource
    • Create a copy of the original
    • Common APIs for graphics processing
    • The beauty 美图秀秀 of the Fool edition
    • Drawing version

The principle of computer graphics representation

The first thing to make clear is that there is a very big difference in the amount of memory required for a picture to be stored in memory and the size of the image needed to fully display on the screen device.

For example, from which we can clearly see this image, the storage space on the hard disk is 303KB, that is, 310,272 bytes. But if you want to display such a picture completely on the screen device, the memory space required is much more than that.

There is a formula for this: The image shows the desired memory = the width of the picture pixels × the height of the picture x the size of each pixel

So how do you know the pixel size? When we click on the image to save the last time, it will appear:

Let's take a look at the meaning of this.

Monochrome bitmap:
Either black or white, only one bit is required to indicate that 1/8 bytes are required to represent a pixel value. In this case the picture above shows up to load into memory required: 1920x1080 * 1/8/1024/1024= 0.2M.
16-bit graph:
Requires 1/21 bytes to represent a pixel value. In this case the chip load into the memory ready display needs: 1920x1080 * 1024/1024 = 1.09M.
256-bit graph:
Indicates that a pixel value needs to be represented by 1 bytes, in which case the slice loaded into the memory preparation display requires: 1920x1080 * 1/1024/1024 = 2.19M.
24-bit bitmap:
Represents a pixel value that requires 3 bytes to represent, in which case the slice loaded into memory ready to be displayed requires: 1920x1080 * 3/1024/1024 = 6.59M.
In the Android operating system, ARGB is used to represent a pixel value
where a represents transparency; In this case, the chip load into the memory preparation display requires: 1920x1080 * 4/1024/1024 = 8.79M.

If the VM heap provided by the system to the app by default is 16M in Andorid, an oom exception will occur without compressing the image.

Loading a large image appears oom

Let's load a big picture and try it, the image resource is below, the size is 1.7M.

Create a project, add a control to the layout, ImageView and MainActivity Locate the control in, and set the picture.

ImageView iv = (ImageView) findViewById(R.id.iv);Bitmap bitmap = BitmapFactory.decodeFile("/mnt/sdcard/dog.jpg");iv.setImageBitmap(bitmap );

The code is simple, and when the runtime comes up with an error, let's see what the error is:

As you can see, the application has applied 30720012 bytes to the system, and then there is a direct outofmemoryerror error.

In the next section, you'll explain how to fix a large map without an oom.

Zoom load a large picture resource

We can see that this picture of the dog is 2400*3200, and our cell phone is just 320*480. If you put it completely directly, there will be an exception, and a waste of resources.

Google engineers have already prepared the solution, and then use BitmapFactory to parse the resource, the image is loaded to obtain the width of the height, and the mobile device to calculate the width of the screen height of the scale, and then to use this scale to load the image resources into memory.

The code is also relatively simple, see:

ImageView IV = (ImageView) Findviewbyid (R.ID.IV);//★1. Use the window Manager to get the width of the phone screenWindowManager wm = (WindowManager) getsystemservice (Window_service);intScreenHeight = Wm.getdefaultdisplay (). GetHeight ();intScreenWidth = Wm.getdefaultdisplay (). GetWidth ();//★2. To get the properties and configuration of a picture without loading it into memoryBitmapfactory.options Options =NewOptions ();///This parameter is set to true that parsing a resource with Bitmapfactory does not return bitmap, but the resource's associated configuration is set: the width of the sample is highOptions.injustdecodebounds =true; Bitmapfactory.decodefile ("/mnt/sdcard/dog.jpg", options);//Get the picture's width highintOutheight = Options.outheight;intOutwidth = Options.outwidth;//★3. Calculating the zoom ratio based on screen width and picture width heightintScale =0;intScaleh = Outheight/screenheight;intScalew = Outwidth/screenwidth;scale = Scaleh > Scalew? Scaleh:scalew;//★4. Parse the picture resource according to the zoom ratio and return to bitmapOptions.injustdecodebounds =false; options.insamplesize = scale; Bitmap Bitmap = Bitmapfactory.decodefile ("/mnt/sdcard/dog.jpg", options); Iv.setimagebitmap (bitmap);
Create a copy of the original

Bitmap that are loaded into memory on Android are not allowed to be modified and can only be modified and painted on their copy. So how do you create a copy of the original image?

The following steps are required:
① Prepare a white paper with the original width and the exact same configuration
② White Paper on the canvas
③, prepare a pen
.
④ Prepare a matrix

The code is also relatively simple, which involves Canvas , and Paint so on, the Matrix following is a simple copy of the original code:

ImageView Srcimageview = (ImageView) Findviewbyid (R.ID.IV_SRC); ImageView Copyimageview = (ImageView) Findviewbyid ( R.id.iv_copy);//OriginalBitmap Srcbitmap = Bitmapfactory.decodefile ("/mnt/sdcard/meinv.jpg"); Srcimageview.setimagebitmap (SRCBITMAP);//Copy//1. Prepare a white paper that is exactly the same as the original width and heightBitmap Copybitmap = Bitmap.createbitmap (Srcbitmap.getwidth (), Srcbitmap.getheight (), Srcbitmap.getconfig ());//2. put the white paper on the canvasCanvas Canvas =NewCanvas (COPYBITMAP);//3. Prepare a penPaint paint =NewPaint ();//4. Prepare a matrixMatrix Matrix =NewMatrix ();//using the specified matrix drawingCanvas.drawbitmap (Srcbitmap, Matrix, paint); Copyimageview.setimagebitmap (COPYBITMAP);

The test results are as follows:

Common APIs for graphics processing

Like learning animation, graphics processing operations are divided into the following categories, the key step of the operation is to use the matrix to change; Google engineers have helped us to encapsulate these operations very well.

Translation:

The code is as follows:

// 原图Bitmap srcBitmap = BitmapFactory.decodeFile("/mnt/sdcard/meinv.jpg");srcImageView.setImageBitmap(srcBitmap);// 拷贝newnewnew Matrix();// ★使用矩阵平移图形matrix.setTranslate(15050);canvas.drawBitmap(srcBitmap, matrix, paint);copyImageView.setImageBitmap(copyBitmap);

The test diagram is as follows:

Scaling:

The scaling code is as follows:

// ★使用矩阵缩放图形// 以图片中心点为原点,缩小0.5倍matrix.setScale(0.50.522);

Test diagram:

Rotating:

The rotation code is as follows:

// ★使用矩阵图形// 以图片中心点为原点,旋转30度matrix.setRotate(30, srcBitmap.getWidth()/2,srcBitmap.getHeight()/2);

Test diagram:

Mirror:

The image code is as follows:

// ★使用矩阵把图片镜像matrix.setScale(-1.01.00);

Test diagram:

Reflection:

The reflection code is as follows:

// ★使用矩阵把图片倒影matrix.setScale(1.0f, -1.0f);matrix.postTranslate(0 , srcBitmap.getHeight());

Test diagram:

The beauty 美图秀秀 of the Fool edition

Purpose, using the color matrix, modify the color value of the picture (simple + humble = Practice practiced hand):

The interface layout is as follows:

Below the layout is a three <SeekBar> layout that modifies the color values of the picture.
The code is as follows:

 Public  class mainactivity extends Activity  implements  Onseekbarchangelistener {    PrivateBitmap Srcbitmap;PrivateSeekBar sb_red;PrivateSeekBar Sb_green;PrivateSeekBar Sb_blue;PrivateImageView IV;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Requestwindowfeature (Window.feature_no_title);        Setcontentview (R.layout.activity_main);        sb_red = (SeekBar) Findviewbyid (r.id.sb_red);        Sb_green = (SeekBar) Findviewbyid (R.id.sb_green);        Sb_blue = (SeekBar) Findviewbyid (R.id.sb_blue);        IV = (ImageView) Findviewbyid (R.ID.IV); Srcbitmap = Bitmapfactory.decodefile ("/mnt/sdcard/meinv.jpg");        Iv.setimagebitmap (SRCBITMAP); Sb_blue.setonseekbarchangelistener ( This); Sb_red.setonseekbarchangelistener ( This); Sb_green.setonseekbarchangelistener ( This); }//Stop sliding    @Override     Public void Onstoptrackingtouch(SeekBar SeekBar) {intCurrentPosition = Seekbar.getprogress ();        Bitmap Copybitmap = Bitmap.createbitmap (Srcbitmap.getwidth (), Srcbitmap.getheight (), Srcbitmap.getconfig ()); Canvas Canvas =NewCanvas (COPYBITMAP); Paint paint =NewPaint ();//★ drawing a picture using a color matrixColorMatrix ColorMatrix =NewColorMatrix ();floatRF =0;floatGF =0;floatBF =0;//Modify the ARGB color value according to the sliding value        Switch(Seekbar.getid ()) { CaseR.ID.SB_RED:RF = currentposition/TenF Break; CaseR.ID.SB_BLUE:BF = currentposition/TenF Break; CaseR.ID.SB_GREEN:GF = currentposition/TenF Break; } colormatrix.set (New float[] {//Rf0,0,0,0,//                        0, GF,0,0,0,//                        0,0, BF,0,0,//                        0,0,0,1,0}); Colorfilter filter =NewColormatrixcolorfilter (ColorMatrix);//★ Set a color matrix filter for a brushPaint.setcolorfilter (filter); Canvas.drawbitmap (Srcbitmap,NewMatrix (), paint);    Iv.setimagebitmap (COPYBITMAP); }//sliding in the process    @Override     Public void onprogresschanged(SeekBar SeekBar,intProgressBooleanFromuser) {}//Start sliding    @Override     Public void Onstarttrackingtouch(SeekBar SeekBar) {    }}

Test results:

There is nothing very important to know about the color matrix on the line.

Drawing version

First look at some of the molding after what kind of bar:

It's pretty funny when you do it yourself.

The following steps are available for drawing artboards:
① prepare a background map
② make a copy of the background map to paint on it
③ Registers a ImageView touch event for one, and when pressed and moved, record the touch point and draw the picture and set it to the Imageview top.
④ Add "bold brush" and "Change color function"

Well, here's a step-by-step.

The first step is to prepare a background map and deposit it into the SD card.


Set the code for the background picture:

iv = (ImageView) findViewById(R.id.iv);srcBitmap = BitmapFactory.decodeFile("/mnt/sdcard/bk.png");iv.setImageBitmap(srcBitmap);

The second step is to make a copy of the background map so that you can paint on it.

// 获取一个拷贝copyBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig());// 获取画布new Canvas(copyBitmap);// 获取画笔new Paint();// 获取一个矩阵new Matrix();canvas.drawBitmap(srcBitmap, matrix, paint);// 画一条直线// canvas.drawLine(0, 0, 100, 100, paint);iv.setImageBitmap(copyBitmap);// 注册触摸事件回调iv.setOnTouchListener(this);

The third step is to register a ImageView touch event for one, record touch points when pressing and moving, and draw pictures and settings to the Imageview top.

//Start coordinate pointPrivate intStartX;Private intStarty;@Override Public Boolean OnTouch(View V, motionevent event) {Switch(Event.getaction ()) { CaseMotionEvent.ACTION_DOWN:startX = (int) Event.getx (); Starty = (int) event.gety (); System.out.println ("Press the coordinate point ("+ StartX +","+ Starty +")"); Break; CaseMotionevent.action_move:intNOWX = (int) Event.getx ();intNowy = (int) event.gety (); System.out.println ("Move the starting coordinate point ("+ StartX +","+ Starty +")"); System.out.println ("Move the end of the coordinate point ("+ Nowx +","+ Nowy +")");        Canvas.drawline (StartX, Starty, Nowx, Nowy, paint);        Iv.setimagebitmap (COPYBITMAP);        StartX = nowx; Starty = Nowy; Break; CaseMOTIONEVENT.ACTION_UP: Break;default: Break; }The //return value is true, the event is consumed and is not passed down;    The //return value is False, the event is not consumed and continues to pass downward;    return true;}

Fourth Step , add "bold brush" and "Change color function"

// 颜色内容int[] colors = { Color.RED, Color.GREEN, Color.BLUE };privateint colorIndex;// 修改颜色publicvoidchangecolor(View v) {    3]);}// 画笔宽度privateint paintWidth;// 加粗画笔publicvoidoverstriking(View v) {    paint.setStrokeWidth(++paintWidth);}

Android Basic Notes (15)-graphics, solving big picture oom, use of painting tools and exercises

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.