Learning notes for Android: bitmap & canvas

Source: Internet
Author: User

Bitmap is the most commonly used resource in our development. After all, a beautiful interface is the most attractive to users.

1. Retrieve bitmap from resource

Bitmapdrawable or bitmapfactory can be used to obtain bitmaps in resources.

Of course, you must first obtain the resource:

Resources res = getresources ();

Bitmapdrawable

  1. Use bitmapdrawable (inputstream is) to construct a bitmapdrawable;
  2. Use getbitmap () of the bitmapdrawable class to obtain the bitmap;
    // Read inputstream and obtain the bitmap inputstream is = res. openrawresource (R. drawable. pic180); bitmapdrawable BMP draw = new bitmapdrawable (is); bitmap BMP = BMP draw. getbitmap ();

Or use the following method:

BitmapDrawable bmpDraw=(BitmapDrawable)res.getDrawable(R.drawable.pic180);Bitmap bmp=bmpDraw.getBitmap();

Use bitmapfactory to obtain bitmap

(Creates bitmap objects from various sources, including files, streams, and byte-arrays .)

Bitmapfactory class decodestream (inputstream is) is used to decode bitmap resources and obtain bitmap resources.

Bitmap BMP = bitmapfactory. decoderesource (Res, R. drawable. pic180 );

All functions of bitmapfactory are static. This helper class can obtain bitmap through resource ID, path, file, and data stream.

The above methods can be freely selected during programming. In the android SDK, the supported image formats are as follows: PNG (preferred), JPG (acceptable), GIF (discouraged ), and BMP (Android SDK support media format ).

2. Obtain bitmap Information

To obtain bitmap information, such as the bitmap size, pixel, density, transparency, and color format, you can obtain bitmap information in the bitmap manual, here, we will only explain the following two points:

  • Bitmap is used for RGB color formats in bitmap. the Config definition only includes alpha_8, argb_4444, argb_8888, and rgb_565. Some other problems are missing, such as rgb_555. You may need to pay attention to this problem during development;
  • Bitmap also provides the compress () interface to compress images. However, androidsak only supports compression in PNG and jpg formats. Android Developers need to add other formats.
3. Display bitmap

You can use the core canvas class to display bitmaps through drawbirmap () of the canvas class, or use bitmapdrawable to draw bitmaps to the canvas. Of course, bitmapdrawable can also be used to display the bitmap to the view.

Convert to bitmapdrawable object display bitmap

// Obtain bitmap BMP = bitmapfactory. decoderesource (Res, R. drawable. pic180); // convert to bitmapdrawable object bitmapdrawable BMP draw = new bitmapdrawable (BMP); // display the bitmap imageview iv2 = (imageview) findviewbyid (R. id. imageview02); iv2.setimagedrawable (BMP draw );

Use the canvas class to display bitmap

Here we use a subclass panel inherited from the view, which is displayed in ondraw of the subclass.

public class MainActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(new Panel(this));    }        class Panel extends View{               public Panel(Context context) {              super(context);         }              public void onDraw(Canvas canvas){              Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);              canvas.drawColor(Color.BLACK);              canvas.drawBitmap(bmp, 10, 10, null);          }      } }

4. Bitmap Scaling

(1) redraw a bitmap as needed. The bitmap after painting is what we need. It is almost the same as the display of the bitmap: drawbitmap (Bitmap bitmap, rect SRC, rect DST, paint ).

(2) Based on the original bitmap, scale the original bitmap to create a new bitmap: createbitmap (bitmap source, int X, int y, int width, int height, matrix m, boolean filter)

(3) Scale (float Sx, float Sy) (preconcat the current matrix
The specified scale.), but note that the entire canvas is scaled.

(4) matrix:

            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);              Matrix matrix=new Matrix();            matrix.postScale(0.2f, 0.2f);            Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),            bmp.getHeight(),matrix,true);            canvas.drawColor(Color.BLACK);              canvas.drawBitmap(dstbmp, 10, 10, null);  

5. Bitmap Rotation

Likewise, bitmap rotation can also be achieved through matrix or canvas.

            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);              Matrix matrix=new Matrix();            matrix.postScale(0.8f, 0.8f);            matrix.postRotate(45);            Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),            bmp.getHeight(),matrix,true);            canvas.drawColor(Color.BLACK);             canvas.drawBitmap(dstbmp, 10, 10, null); 

Rotation effect:

 

6. Image Watermark Generation Method

The process of generating a watermark. There are three steps: first, loading the original image; second, loading the watermark image; and third, saving the new image.

/*** Create the bitmap from a byte array ** @ Param SRC the bitmap object you want proecss * @ Param watermark the water mark abve the SRC * @ return a bitmap object, if paramter's length is 0, return NULL */private bitmap createbitmap (Bitmap SRC, bitmap watermark) {string tag = "createbitmap"; log. D (TAG, "Create a New bitmap"); If (src = NULL) {return NULL;} int W = SRC. getwidth (); int H = SRC. getheight (); int WW = watermark. getwidth (); int wh = watermark. getheight (); // create the new blank Bitmap bitmap newb = bitmap. createbitmap (W, H, config. argb_8888); // create a new bitmap canvas CV = new canvas (NEWB) with the same width as SRC; // draw SRC into cv. drawbitmap (SRC, 0, 0, null); // draw SRC at coordinates 0, 0 // draw watermark into cv. drawbitmap (watermark, W-ww + 5, H-Wh + 5, null); // Add the watermark to the bottom right corner of SRC // save all clip cv. save (canvas. all_save_flag); // save // store cv. restore (); // store return newb ;}

7. Save and restore of canvas

The ondraw method will pass in a canvas object, which is the canvas you use to draw the visual interface of the control.

In the ondraw method, we often see that the SAVE and restore methods are called. What are they used?

Saved save: used to save the canvas status. After saving, you can call operations such as pan, zoom, rotate, miscut, and crop of the canvas.

Restore restore: used to restore the State saved before the canvas. This prevents operations performed on the canvas after the save operation from affecting subsequent painting.

Save and restore must be used together (Restore can be less than save, but not more). If the restore calls more than save, an error is thrown.The SAVE and restore operations on canvas are often mixed.

For example, we first want to draw a right arrow in the canvas. Of course, we can draw it directly. In addition, we can also rotate the canvas 90 ° and draw an up arrow first, and then rotate back (this rotation operation is very useful for marking on the circumference ). Then, if we want to have a 20-pixel circle in the lower right corner, the core code in ondraw is:

int px = getMeasuredWidth();int py = getMeasuredWidth();// Draw backgroundcanvas.drawRect(0, 0, px, py, backgroundPaint);canvas.save();canvas.rotate(90, px/2, py/2);                // Draw up arrowcanvas.drawLine(px / 2, 0, 0, py / 2, linePaint);                canvas.drawLine(px / 2, 0, px, py / 2, linePaint);canvas.drawLine(px / 2, 0, px / 2, py, linePaint);canvas.restore();// Draw circlecanvas.drawCircle(px - 10, py - 10, 10, linePaint);

Result 1:

What will it look like if we don't call save and restore? 2:

From the two graphs, we can see the obvious difference in the circle position. Without the SAVE and restore operations on the canvas, all images are drawn on the canvas after 90 ° rotation. After the ondraw method is executed, the canvas is automatically restored. When the SAVE and restore operations are executed differently, the drawing may be different.

Article transferred from: http://www.cnblogs.com/feisky/archive/2010/01/10/1643460.html

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.