Android realizes round, rounded and oval custom picture view (using Bitmapshader Graphics Rendering method)

Source: Internet
Author: User

I. Overview

Android enables graphics such as rounded rectangles, circles, or ellipses, typically a custom view plus the use of xfermode. There are many ways to realize rounded pictures, and the common use is xfermode,shader. This article directly inherits ImageView, uses the Bitmapshader method to realize the circle, the rounded angle and the ellipse drawing, waits everybody to see my this article the method, other similar shape also can all extrapolate come to draw out.

Two:

Iii. introduction of Bitmapshader

Bitmapshader is a subclass of Shader that can be set by Paint.setshader (Shader Shader),

Here we only focus on Bitmapshader, the construction method:

Mbitmapshader = new Bitmapshader (bitmap, Tilemode.clamp, Tilemode.clamp);

Parameter 1:bitmap

Parameter 2, parameter 3:tilemode;

There are three types of Tilemode:

CLAMP stretching

REPEAT Repeat

MIRROR Mirroring

If you set the screen screensaver, if the picture is too small, you can choose to repeat, stretch, mirror;

repeat: this bitmap is repeated horizontally and vertically.

Mirror: The cross is constantly flipping and repeating;

Stretch: This and the computer screensaver should be a little different, this stretch is the last pixel of the picture, the last horizontal row of pixels, continuous repetition, the column of the vertical line of pixels, constantly repeating;

Public Bitmapshader(Bitmap bitmap,shader.tilemode tilex,shader.tilemode Tiley)

Call this method to produce a renderer (Shader) that draws a bitmap.

Bitmap bitmaps used within the renderer

Tilex the tiling mode for x to draw the bitmap in. X-Directional tile pattern on the bitmap

Tiley the tiling mode for Y-draw the bitmap in. Y-Direction tile pattern on the bitmap

Tilemode: (a total of three kinds)

CLAMP: If the renderer exceeds the original boundary range, the range edge staining is copied.

REPEAT: Landscape and portrait Repeat renderer picture, tiled.

MIRROR: Horizontal and vertical duplicate renderer picture, this is not the same as the REPEAT repetition, he is tiled in a mirrored manner.

Iv. implementation of a picture view with custom circles, rounded corners, and ellipses

1. Measure the size of the view

@Overrideprotected voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec) {        //TODO auto-generated Method Stub        Super. Onmeasure (Widthmeasurespec, Heightmeasurespec); //If you are drawing a circle, force the width to be the same size        if(Mtype = =type_circle) {Mwidth=math.min (Getmeasuredwidth (), Getmeasuredheight ()); Mradius= MWIDTH/2;        Setmeasureddimension (Mwidth, mwidth); }    }

2. Set Bitmapshader and brush paint

/*** Set Bitmapshader*/    Private voidSetbitmapshader () {drawable drawable=getdrawable (); if(NULL==drawable) {            return; } Bitmap Bitmap=Drawabletobitmap (drawable); //Create a Bitmapshader by bitmap as a shaderMbitmapshader =NewBitmapshader (Bitmap, Tilemode.clamp, Tilemode.clamp); floatScale = 1.0f; if(Mtype = =type_circle) {            //get a small value of bitmap wide or high            intBsize =math.min (Bitmap.getwidth (), Bitmap.getheight ()); Scale= Mwidth * 1.0f/bsize; } Else if(mtype = = Type_round | | mtype = =type_oval) {            //if the width or height of the picture does not match the width and height of the view, the scale of the image needs to be scaled; the width of the scaled picture must be greater than the width of our view, so we take a large value here;Scale = Math.max (getwidth () * 1.0f/bitmap.getwidth (), getheight () * 1.0f/bitmap.getheight ()); }        //Shader's transformation matrix, which we're mainly used to zoom in or outMmatrix.setscale (scale, scale); //Setting the transformation matrixMbitmapshader.setlocalmatrix (Mmatrix);    Mpaint.setshader (Mbitmapshader); }

3. Finally, the picture is drawn with rounded corners, circles and ellipses, certainly in the OnDraw, the basic principle is to use the above Mbitmapshader rendering brush to draw

@Overrideprotected voidOnDraw (canvas canvas) {if(NULL==getdrawable ()) {            return;        } setbitmapshader (); if(Mtype = =type_circle)        {canvas.drawcircle (Mradius, Mradius, Mradius, Mpaint); } Else if(Mtype = =type_round)            {Mpaint.setcolor (color.red);        Canvas.drawroundrect (Mrect, Mroundradius, Mroundradius, Mpaint); }Else if(Mtype = =type_oval)        {Canvas.drawoval (mrect, mpaint); }    }

V. View layout implementation

This is simple, 3 custom view:

<scrollview xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Tools:context=". Mainactivity "> <LinearLayout android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"android:gravity= "Center_horizontal"Android:layout_margintop= "5DP"Android:layout_marginbottom= "25DP"android:orientation= "Vertical" > <Com.czm.viewdrawtest.XCRoundAndOvalImageView Android:id= "@+id/cicleimageview"Android:layout_width= "200DP"Android:layout_height= "200DP"android:src= "@drawable/img1"/> <Com.czm.viewdrawtest.XCRoundAndOvalImageView Android:id= "@+id/roundrectimageview"Android:layout_width= "200DP"Android:layout_height= "240DP"Android:layout_margintop= "5DP"android:src= "@drawable/img2"/> <Com.czm.viewdrawtest.XCRoundAndOvalImageView Android:id= "@+id/ovalimageview"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_margintop= "5DP"android:src= "@drawable/img3"/> </LinearLayout></ScrollView>

Vi. use and testing of custom view

The above directly drawn custom view is finished, the following is the use of this view, using the same method as normal ImageView, as a normal control to use.

 Packagecom.czm.viewdrawtest;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.Window;ImportAndroid.view.WindowManager;/*** Use custom ImageView *@authorcaizhiming **/ Public classMainactivityextendsActivity {PrivateXcroundandovalimageview Circleimageview;//Circular Picture    PrivateXcroundandovalimageview Roundrectimageview;//Rounded Rectangle Picture    PrivateXcroundandovalimageview Ovalimageview;//Oval Image@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Set Untitledrequestwindowfeature (Window.feature_no_title); //Set Full ScreenGetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, Windowmanager.layoutparams.          Flag_fullscreen);                Setcontentview (R.layout.activity_main);    Initviews (); }    /*** Initialize views*/    Private voidinitviews () {Circleimageview=(Xcroundandovalimageview) Findviewbyid (R.id.cicleimageview); Roundrectimageview=(Xcroundandovalimageview) Findviewbyid (R.id.roundrectimageview); Ovalimageview=(Xcroundandovalimageview) Findviewbyid (R.id.ovalimageview);        Roundrectimageview.settype (Xcroundandovalimageview.type_round); Roundrectimageview.setroundradius (100);        Ovalimageview.settype (Xcroundandovalimageview.type_oval); Ovalimageview.setroundradius (50); }}

Vii. Source code Download:

Real theme park NET: http://www.zhentiyuan.com

SOURCE Download: http://download.csdn.net/detail/jczmdeveloper/8303717

Android realizes round, rounded and oval custom picture view (using Bitmapshader Graphics Rendering method)

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.