Android BitmapShader implements circular and rounded pictures,
Reprinted please indicate the source: bytes
I remember that I wrote a blog post about Android which perfectly implemented image rounded corners and circles (for implementation analysis). It mainly implemented a custom View and Xfermode. In fact, there are many methods to achieve the rounded corner image. The common method is to use Xfermode and Shader. This blog will inherit the ImageView directly and use BitmapShader to draw the rounded corner. If you are able to read it, I estimate that all shapes can be drawn.
2,
This is a demonstration image of the rounded corner ~~ There is nothing to say, just set the size of the rounded corner;
This is a circular display chart. Pay attention to it here, because the set image may be a rectangle. For example, there are two rectangles, one being wide and the other being large;
If we want to display the image as a circle, we may need to zoom in or out the circle (because the width of the image may not meet the length of the side, but the height exceeds, in this case, we need to enlarge its width ).
In this figure, the center is the normal size. The top and bottom are the special sizes. We need to enlarge or reduce the size when the size is greater than or less than the set size;
If the width and height of the image are different from those of the view during the rounded corner, you need to zoom in and out the image. Here you cannot see it in the code.
3. Talking about BitmapShader
BitmapShader is a sub-class of Shader. You can use Paint. setShader (Shader shader) to set,
Here we only focus on BitmapShader. The constructor is as follows:
MBitmapShader = new BitmapShader (bitmap, TileMode. CLAMP, TileMode. CLAMP );
Parameter 1: bitmap
Parameter 2, parameter 3: TileMode;
There are three TileMode values:
CLAMP stretch
REPEAT already exists.
MIRROR Image
If you set screen saver for your computer screen and the image is too small, you can repeat, stretch, or mirror;
Repeat:This bitmap is repeated horizontally and vertically.
Image:Repeated horizontal flip and vertical flip;
Stretch:The screen saver mode should be somewhat different from the screen saver mode of the computer. This stretch is the last pixel of the image; the last horizontal pixel is rampant, repeated, and the column of pixels of the vertical item, constant repetition;
Now I understand that BitmapShader sets the image to mPaint and then colors the image area based on the TileMode you set when drawing the image with this mPaint.
Note that BitmapShader is drawn from the upper-left corner of your canvas, rather than a square in the lower-right corner of the view, it will not start in the upper-left corner of your square.
Now, I believe you have a certain understanding of BitmapShader. Of course, if you want to fully understand the Shader, please refer to the God of Love Songs: custom Controls are actually quite simple.
We set the CLAMP mode for our rounded corners and circles, but will you have a question:
Does the view stretch if its width or height is higher than our bitmap's width or height?
Well, we will set a matrix for BitmapShader to properly zoom in or out the image, and will not set the condition that "view width or height is higher than our bitmap width or height.
At this point, we have completed the basic introduction of the principle, obtained the drawable into bitmap, then initialized BitmapShader directly, set Shader with the paint brush, and finally completed the circle in onDraw.
4. BitmapShader practice
First, let's take a look at the circular or rounded corner implemented by using BitmapShader.
Here we inherit the ImageView directly, so that you will be familiar with the image setting code. But we need to support two modes, so we need to customize the attributes:
1. Custom Attributes
Values/attr. xml
<?xml version="1.0" encoding="utf-8"?><resources> <attr name="borderRadius" format="dimension" /> <attr name="type"> <enum name="circle" value="0" /> <enum name="round" value="1" /> </attr> <declare-styleable name="RoundImageView"> <attr name="borderRadius" /> <attr name="type" /> </declare-styleable></resources>
We define an enumeration and a borderRadius rounded corner.
2. Get Custom Attributes
Public class RoundImageView extends ImageView {/*** image type, circular or rounded corner */private int type; private static final int TYPE_CIRCLE = 0; private static final int TYPE_ROUND = 1; /*** default rounded corner size */private static final int BODER_RADIUS_DEFAULT = 10;/*** rounded corner size */private int mBorderRadius; /*** Paint */private Paint mBitmapPaint;/*** radius of the rounded corner */private int mRadius;/*** 3x3 matrix, it is mainly used to zoom in and zoom out */private Matrix mMatrix;/*** to render an image and color it with an image */private BitmapShader mBitmapShader; /*** view width */private int mWidth; private RectF mRoundRect; public RoundImageView (Context context, AttributeSet attrs) {super (context, attrs ); mMatrix = new Matrix (); mBitmapPaint = new Paint (); mBitmapPaint. setAntiAlias (true); TypedArray a = context. obtainStyledAttributes (attrs, R. styleable. roundImageView); mBorderRadius =. getDimensionPixelSize (R. styleable. roundImageView_borderRadius, (int) TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_DIP, BODER_RADIUS_DEFAULT, getResources (). getDisplayMetrics (); // The default value is 10 dptype =. getInt (R. styleable. roundImageView_type, TYPE_CIRCLE); // The default value is Circlea. recycle ();}
We can see that some of our member variables are annotated. Then, we get our custom attributes in the constructor and some variable initialization.
3. onMeasure
@ Overrideprotected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {Log. e ("TAG", "onMeasure"); super. onMeasure (widthMeasureSpec, heightMeasureSpec);/*** if the type is circular, the width and height of the view must be changed to be consistent. Take the small value as the standard */if (type = TYPE_CIRCLE) {mWidth = Math. min (getMeasuredWidth (), getMeasuredHeight (); mRadius = mWidth/2; setMeasuredDimension (mWidth, mWidth );}}
The onMeasure method is rewritten to force the width and height of the view to be consistent when the set type is circular.
The next step is to set BitmapShader and plot
4. Set BitmapShader
/*** Initialize BitmapShader */private void setUpShader () {Drawable drawable = getDrawable (); if (drawable = null) {return;} Bitmap bmp = drawableToBitamp (drawable ); // use bmp as the coloring tool, that is, to draw bmp mbitmapshader = new BitmapShader (bmp, TileMode. CLAMP, TileMode. CLAMP); float scale = 1.0f; if (type = TYPE_CIRCLE) {// get the bitmap width or height of the small value int bSize = Math. min (bmp. getWidth (), bmp. getHeight (); scale = mWidth * 1.0f/bSize;} else if (type = TYPE_ROUND) {// if the width or height of the image does not match the width and height of the view, calculate the scaling ratio. The scaled image width and height must be greater than the width and height of our view. max (getWidth () * 1.0f/bmp. getWidth (), getHeight () * 1.0f/bmp. getHeight ();} // The shader transformation matrix. Here we mainly use it to zoom in or out of mMatrix. setScale (scale, scale); // sets the transform matrix mBitmapShader. setLocalMatrix (mMatrix); // sets shadermBitmapPaint. setShader (mBitmapShader );}
In setUpShader, we first convert drawable into our bitmap;
Then initialize mBitmapShader = new BitmapShader (bmp, TileMode. CLAMP, TileMode. CLAMP );
Next, calculate the scale based on the type and the width and height of bitmap and view;
Scale calculation:
Round: take the small value of the width or height of the bitmap as the benchmark. If we use the round value, we cannot fill the circular area after scaling. Then, the mWidth/bSize of the view; is the scale.
Rounded corner: Because the width/high ratio is designed, getWidth () * 1.0f/bmp. getWidth () and getHeight () * 1.0f/bmp. getHeight (); finally, get the cursor, because the final scaled image must be larger than the area of our view, a bit similar to centerCrop;
For example, the width and height of a view are 10*20, and the width and height of an image are 5*100. In the end, we should scale up the image based on the width instead of the height; because we need to customize the scaled image to be greater than the width and height of our view, and ensure the ratio of the original image.
With scale, you can set the matrix for us;
Then use mBitmapShader. setLocalMatrix (mMatrix );
Finally, set bitmapShader to paint.
Code for converting drawable to bitmap:
/* Drawable to bitmap ** @ param drawable * @ return */private Bitmap outputs (Drawable drawable) {if (drawable instanceof BitmapDrawable) {BitmapDrawable bd = (BitmapDrawable) drawable; return bd. getBitmap ();} int w = drawable. getIntrinsicWidth (); int h = drawable. getIntrinsicHeight (); Bitmap bitmap = Bitmap. createBitmap (w, h, Bitmap. config. ARGB_8888); Canvas canvas = new Canvas (bitmap); drawable. setBounds (0, 0, w, h); drawable. draw (canvas); return bitmap ;}
Finally, we will call setUpShader () in onDraw and draw it.
5. Draw
At this point, we have to draw the last step, because our range and scaling are complete, so we only have to draw.
@ Overrideprotected void onDraw (Canvas canvas) {if (getDrawable () = null) {return;} setUpShader (); if (type = TYPE_ROUND) {canvas. drawRoundRect (mRoundRect, mBorderRadius, mBorderRadius, mBitmapPaint);} else {canvas. drawCircle (mRadius, mBitmapPaint); // drawSomeThing (canvas) ;}@ Overrideprotected void onSizeChanged (int w, int h, int oldw, int oldh) {super. onSizeChanged (w, h, oldw, oldh); // the range of the rounded corner image, if (type = TYPE_ROUND) mRoundRect = new RectF (0, 0, getWidth (), getHeight ());}
It's easy to draw. Draw a circle, a rounded rectangle or something. The limited range of the rounded rectangle is mRoundRect initialized in onSizeChanged.
5. State storage and recovery. Of course, if the memory is insufficient, and our Activity is placed in the background, it is restarted unfortunately, or the user rotates the screen to restart the Activity, our View should be able to save its own attributes as much as possible. What is the purpose of status saving? For example, if the current rounded corner is 10 DP and the user clicks it and changes it to 50 DP, after the user rotates or is placed in the background for a long time, the returned Activity should still be 50 DP; we can simply store the current type and mBorderRadius.
private static final String STATE_INSTANCE = "state_instance";private static final String STATE_TYPE = "state_type";private static final String STATE_BORDER_RADIUS = "state_border_radius";@Overrideprotected Parcelable onSaveInstanceState(){Bundle bundle = new Bundle();bundle.putParcelable(STATE_INSTANCE, super.onSaveInstanceState());bundle.putInt(STATE_TYPE, type);bundle.putInt(STATE_BORDER_RADIUS, mBorderRadius);return bundle;}@Overrideprotected void onRestoreInstanceState(Parcelable state){if (state instanceof Bundle){Bundle bundle = (Bundle) state;super.onRestoreInstanceState(((Bundle) state).getParcelable(STATE_INSTANCE));this.type = bundle.getInt(STATE_TYPE);this.mBorderRadius = bundle.getInt(STATE_BORDER_RADIUS);} else{super.onRestoreInstanceState(state);}}
The code is relatively simple. In the demo in our article, the first and fourth items can be clicked, And the clicking will change. You can click and then rotate the screen for testing.
At the same time, we have released two methods to dynamically modify the rounded corner size and type.
public void setBorderRadius(int borderRadius){int pxVal = dp2px(borderRadius);if (this.mBorderRadius != pxVal){this.mBorderRadius = pxVal;invalidate();}}public void setType(int type){if (this.type != type){this.type = type;if (this.type != TYPE_ROUND && this.type != TYPE_CIRCLE){this.type = TYPE_CIRCLE;}requestLayout();}}public int dp2px(int dpVal){return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpVal, getResources().getDisplayMetrics());}
Finally, paste our layout file and MainActivity.
6. Call the layout file:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:zhy="http://schemas.android.com/apk/res/com.zhy.variousshapeimageview" android:layout_width="match_parent" android:layout_height="wrap_content" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.zhy.view.RoundImageView android:id="@+id/id_qiqiu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/qiqiu" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:layout_width="200dp" android:layout_height="200dp" android:layout_margin="10dp" android:src="@drawable/aa" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/icon" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:id="@+id/id_meinv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/aa" zhy:borderRadius="20dp" zhy:type="round" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/icon" zhy:borderRadius="40dp" zhy:type="round" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/qiqiu" zhy:borderRadius="60dp" zhy:type="round" > </com.zhy.view.RoundImageView> </LinearLayout></ScrollView>
No, ScrollView has a linear layout with a pile of roundimageviews.
MainActivity
package com.zhy.variousshapeimageview;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import com.zhy.view.RoundImageView;public class MainActivity extends Activity{private RoundImageView mQiQiu;private RoundImageView mMeiNv ; @Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mQiQiu = (RoundImageView) findViewById(R.id.id_qiqiu);mMeiNv = (RoundImageView) findViewById(R.id.id_meinv);mQiQiu.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){mQiQiu.setType(RoundImageView.TYPE_ROUND);}});mMeiNv.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){mMeiNv.setBorderRadius(90);}});}}
Now, this blog is over. You can try to draw a pentagon or Shenma shape, or add a border Shenma. I believe it is okay to modify it ~~ The Code may have bugs and deficiencies. You are welcome to point out and make progress together.
Last:
Download source code
Bytes ----------------------------------------------------------------------------------------------------------
Some of the bloggers have already been online. If you do not like boring text, stamp it (for initial record, we look forward to your support ):
1. scratch cards for Android custom controls in e-commerce activities
2. Android custom controls create Android streaming layout and popular labels
3. Implementation of Android intelligent robot xiaomu
4. High imitation QQ5.0 slide
5. High imitation 5.2.1 main interface and message reminder