Reprinted: Detailed description and practice of the Shader of the 18-weapon Android drawing Canvas (I), androidcanvas

Source: Internet
Author: User

Reprinted: Detailed description and practice of the Shader of the 18-weapon Android drawing Canvas (I), androidcanvas
Preface

In Android, plotting is indispensable.CanvasNow,CanvasIs a huge knowledge system with Java layer and jni layer deep into the Framework.CanvasThere is a lot of knowledge and content, and a general weapon library is built,PaintYesCanvasBut today we are not talking aboutCanvasNeitherPaint, ButPaintRelated Knowledge pointsShader.

What is Shader?

The Shader is interpreted as a shadow in the English dictionary. Check Wikipedia and draw the following conclusions:

In the field of computer graphics, a shader is a computer program that is used to do shading: the production of appropriate levels of color within an image, or, in the modern era, also to produce special effects or do video post-processing. A definition in layperson's terms might be given as "a program that tells a computer how to draw something in a specific and unique way.

In the computer graphics field, a Shader is a computer program used for coloring. It is usually used to generate a color value of an appropriate level in an image or to generate special visual effects, or process the video. From a non-professional perspective, it can be described as "a program that tells computers how to draw images by some special means ".

It seems abstract and difficult to understand, but I think it is appropriate to correctly understand its definition, which allows us to truly write very efficient code.

Android also has the Shader concept. Compared with the above definition, it should also be a kind of thing that produces some special effects on the graphic screen. Is that true? I can tell you the answer first-yes.
To increase your interest in Shader, let's take a look at some of the clips obtained through Shader.

Is it interesting? If you are interested in this, follow my pace and read the following content.

Knowledge about Shader in Android

When I look at the API and finally don't want FQ, I still don't have FQ. When I want to see the API, I directly go to www.androidxref.com to view the source code. Now you can go to the Chinese page on the official website to view the information. In Android, the Shader API address is Shader.

Shader in Android is explained in this way.

The Shader is a base class object. It returns the color value of the segment during drawing and calls the Paint. the setShader () method can install its sub-class into the Paint brush, so that the color obtained by the Paint object during painting is from the Shader object.

The Shader subclass is mentioned above,Shader5 subclassBitmapShader,ComposeShader,LinearGradient,RadialGradient,SweepGradient. The purpose of this article is to talk about its sub-classes separately.

Image Renderer BitmapShader

BitmapShader treats an image as a texture (in OpenGL, texture is the meaning of a texture, which can be understood as a text without color being attached to an image, in this way, the visual effect is a square image. In this image, you can set the tiling mode of BitmapShader to achieve mirroring and repetition.

BitmapShader (Bitmap bitmap,                 Shader.TileMode tileX,                 Shader.TileMode tileY)

The above is the construction method of BitmapShader.

Bitmap is a fingerprint image, and tileX is the tiling modetileY of the X axis, which is the tiling mode of the Y axis.

Many may have questions about the TileMode?

Mysterious TileMode

What is TileMode?
In fact, it is just an enumeration. It has only three values.

Shader.TileMode CLAMPShader.TileMode MIRRORShader.TileMode REPEAT
CLAMP

It means that when the range to be drawn is greater than the range of the Image Texture itself, the extra space position will be filled by the edge color of the texture image. It is difficult to explain the text. I will use images instead.
The source image is as follows:

The resolution of the source image is 562*336.

Let's write a custom View-mmview. Then in itsonDraw()Method, and set the Shader of the paint brush to BitmapShader. the tiling mode of the Shader is CLAMP.
The Code is as follows:

@Overrideprotected void onDraw(Canvas canvas) {    super.onDraw(canvas);    int w = getWidth();    int h = getHeight();    Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.yourname);    mShader = new BitmapShader(bmp, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);    mPaint.setShader(mShader);    canvas.drawRect(0,0,w,h,mPaint); }

You only need to pay attentionmShader = new BitmapShader(bmp, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);This line of code is enough, and the rest will be explained later.

In the layout file of MainActivity, we add this custom View.

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.frank.gradientdemo.MainActivity">    <com.frank.gradientdemo.CustomView        android:layout_width="match_parent"        android:layout_height="400dp" /></RelativeLayout>

We can see that the width of CustomView occupies the entire screen of the mobile phone, and the height is 400dp.
In the code, draw a rectangle with the width and height of mmview and use the image above as the texture. The effect is as follows:

:

It seems a little different from the source image?What is outside the red box? Let's turn the phone into a landscape screen.

This double is different! The right side of the red box is similar to the bottom. 
Let's focus on the definition of CLAMP.

It means that when the range to be drawn is greater than the range of the Image Texture itself, the extra space position will be filled by the edge color of the texture image.

Based on the examples, we should be able to understand its meaning. In the above example, if the texture itself is smaller than the area to be drawn, the excess part will be filled with the color of the edge. Therefore, the above phenomenon is caused. Let's take a closer look. Let's look at the next knowledge point.

MIRROR

This mode allows the texture to be copied in the X and Y directions in the image mode.

This mode is easy to understand.

@Overrideprotected void onDraw(Canvas canvas) {    super.onDraw(canvas);    int w = getWidth();    int h = getHeight();    Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.yourname);    mShader = new BitmapShader(bmp, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);    mPaint.setShader(mShader);    canvas.drawRect(0,0,w,h,mPaint);}

 

This is the effect of the image.

REPEAT

It copies the image texture along the XY axis. What does it mean? I can understand the figure. Here, I want to change an image to demonstrate the effect.

The Code is as follows:

@Overrideprotected void onDraw(Canvas canvas) {    super.onDraw(canvas);    int w = getWidth();    int h = getHeight();    Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.repeat);    mShader = new BitmapShader(bmp, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);    mPaint.setShader(mShader);    canvas.drawRect(0,0,w,h,mPaint);}

Effect:

Wow !!! Many puppies.

Do you think the Repeat mode is particularly useful? A graph fills up the entire space.

Mixed Doubles

The content mentioned above is the same mode for the XY direction. Can it be used together?

X --> clamp y --> MIRROR
mShader = new BitmapShader(bmp, Shader.TileMode.CLAMP, Shader.TileMode.MIRROR);

The dog looks even more sad.

X --> mirror y --> CLAMP
mShader = new BitmapShader(bmp, Shader.TileMode.MIRROR, Shader.TileMode.CLAMP);

 

 
A little scary, isn't it?

X --> clamp y --> REPEAT
mShader = new BitmapShader(bmp, Shader.TileMode.CLAMP, Shader.TileMode.REPEAT);

You can see that the right part is stretched, and then the same image is copied up and down.

X --> repeat y --> CLAMP
mShader = new BitmapShader(bmp, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);

 

We can see that the copy is performed on the right side, and the stretch is performed below.

X --> repeat y --> MIRROR
mShader = new BitmapShader(bmp, Shader.TileMode.REPEAT, Shader.TileMode.MIRROR);

 

Copy on the right. The image is shown below.

X --> mirror y --> REPEAT
mShader = new BitmapShader(bmp, Shader.TileMode.MIRROR, Shader.TileMode.REPEAT);

 

 
On the right is the image, and below is the copy of the image above.

Okay, TILEMODE is finished. Let's go to the topic (it's strange. Isn't this article about TILEMODE ?)

BitmapShader (Bitmap bitmap,                 Shader.TileMode tileX,                 Shader.TileMode tileY)

Let's review its construction method. bitmap is a texture image. We already know the meaning and usage of two TileMode parameter objects. Now let's take a look at its usage.

@ Overrideprotected void onDraw (Canvas canvas) {super. onDraw (canvas); int w = getWidth (); int h = getHeight (); int radius = w <= h? W/2: h/2; // 1 parse bitmap object Bitmap bmp = BitmapFactory. decodeResource (getResources (), R. drawable. repeat); // 2 generate BitmapShader with bitmap object, and set TILEMODE mShader = new BitmapShader (bmp, Shader. tileMode. REPEAT, Shader. tileMode. REPEAT); // 3 install the BitmapShader object on the paint brush object mPaint. setShader (mShader); // 4 draw a canvas with the paint brush. drawCircle (w/2, h/2, radius, mPaint );}

The above code is to draw a circle, and then use the picture to duplicate the graph. The effect is as follows:

Is it quite appealing? The effect is the same as that of the custom circular image control. This puppy sadly reminds me of Mei Qian and Liu da in Jia's passing by your world.

Let's think about how to write the circular image control code again?
As we all know, you can set it first.canvasDraw an image and set the Xfermode of the paint brush.Paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));Then draw a circle.

Now we try to use BitmapShader to write such a function.
Ideas:
1. First, make sure that the custom View is square.
2. Create a BitmapShader for the target image and set it to the paint brush.
3. Use the set paint brush to draw a circle using Canvas.
4. The key point is that we need to adjust the size of the original bitmap so that its width to height must be equal to the radius of the circle.

Now, write the code.

Public class CustomView extends View {private Paint mPaint; private Shader mShader; public CustomView (Context context) {this (context, null);} public CustomView (Context context, AttributeSet attrs) {this (context, attrs, 0);} public CustomView (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr); mPaint = new Paint (); mPaint. setAntiAlias (true) ;}@ Override p Rotected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {super. onMeasure (widthMeasureSpec, heightMeasureSpec); // set the dimensions to 400*400 setMeasuredDimension (400,400) for ease of demonstration;} @ Override protected void onDraw (Canvas canvas) {super. onDraw (canvas); int w = getWidth (); int h = getHeight (); int radius = w <= h? W/2: h/2; // The original Bitmap bmp = BitmapFactory. decodeResource (getResources (), R. drawable. repeat); // create a scaled image with the target width and height. Bitmap result = Bitmap. createScaledBitmap (bmp, w, h, false); // create BitmapShader mShader = new BitmapShader (result, Shader. tileMode. REPEAT, Shader. tileMode. REPEAT); mPaint. setShader (mShader); // draw a circle canvas. drawCircle (w/2, h/2, radius, mPaint );}}

:

The injured puppy came out again.

The functionality of X.

We already know how to use BitmapShader to render a rectangle or circle, but what's amazing about it ???

Of course not !!!A Shader is called a shadow used to render objects. In the OPENGL 3d world, a texture can be viewed as the skin of a bare model. It can be used to color a style, ball, or even a complex portrait model. In the scope of Canvas, Shader must be used only for 2d plane coloring. In addition to Rectangles and circles, Shader must also be applicable to triangles and other polygon and any closed irregular shapes, what is an irregular graph?

Isn't text counted ???
Figure-based speech:

The image of the puppy is pasted into the text. The code is very simple.

Bitmap bmp = BitmapFactory. decodeResource (getResources (), R. drawable. repeat); mShader = new BitmapShader (bmp, Shader. tileMode. REPEAT, Shader. tileMode. REPEAT); mPaint. setTextSize (200366f); mPaint. setColor (Color. RED); mPaint. setTypeface (Typeface. DEFAULT_BOLD); mPaint. setShader (mShader); canvas. drawText ("puppy", 0, h/2, mPaint );

Okay, I'm done with it.

I was going to talk aboutComposeShader,LinearGradient,RadialGradient,SweepGradientDue to the length of the article, let's talk about it separately. The next section describes other Shader sub-classes.

Detailed description and practice of Shader for 18 weapons in Android Canvas (Part II)

 

Related Article

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.