Basic Android tutorial -- 13 Drawable types in Android 8.1.1 summary Part 1

Source: Internet
Author: User
Tags getcolor

Basic Android tutorial -- 13 Drawable types in Android 8.1.1 summary Part 1
This section introduces:

Starting from this section, we will learn some basic knowledge about drawing and animation in Android, and customize the advanced section.
Lay the foundation! In the first section, we will deduct the Drawable in Android! Android provides up to 13 types
Drawable. In this section, we will repeat it one by one!

Precautions for using Drawable Resources
Drawable can be divided into two types:
One is that we Common image resourcesIn Android Studio, we usually put it under the res/mipmap directory,
Different from the previous Eclipse! In addition, if we switch the project to the Android project mode, we can directly
You can drop an image in the directory of mipmap. AS will automatically split hdpi, xhdpi ...!
The other is written by us. Drawable resources in XML formatWe usually put them in the res/drawable directory.
For example, click the most common button to switch to the Selctor! In XML, we can directly set drawable through @ mipmap or @ Drawable.
For example, android: background = "@ mipmap/iv_icon_zhu"/"@ drawable/btn_back_selctor"
In Java code, we can use getDrawable (R. mipmap. xxx) of Resource to obtain drawable resources.
To set a background for a control, such as ImageView, we can directly call the control. getDrawale ()
You can obtain the drawable object! Resource names in drawable in Android must be: [A-z0-9 _.](That is, it can only contain letters, numbers, underscores (_), and periods .),
And cannot begin with a number, otherwise the compilation will report the error: Invalid file name: must contain only [a-z0-9 _.]!
Lower case !!!! Lower case !!! Lowercase! -- Three important events ~

Okay, you should pay attention to this. Next we will learn the 13 Drawable types provided by Android!

1. ColorDrawable

The simplest Drawable. When we draw a ColorDrawable onto a Canvas,
A fixed color will be used to fill the painting, and then draw a monochrome area on the canvas!

1) define ColorDrawable in Java:
ColorDrawable drawable = new ColorDrawable(0xffff2200);  txtShow.setBackground(drawable);  
2) define ColorDrawable in xml:

    
    
  

Of course, the above usage is not used much. More often, we create a color. xml file under the res/values directory.
File, and then write the color value to be used into it. When necessary, obtain the corresponding value through @ color, such:

3) create a color. xml file.

For example:


    
        
   
    #fff5f5f5
       
   
    #ffe0e0e0
       
   
    #fffafafa
       
   
    #ff757575
       
   
    #ff424242
       
   
    #ff303030
       
   
    #ff212121
   
    

Then, if it is in an xml file, we can get the corresponding color value through @ color/xxx.
In Java:

int mycolor = getResources().getColor(R.color.mycolor);    btn.setBackgroundColor(mycolor);  

Ps: Note that if we directly define the color value in Java, 0x should be added, and transparency should not be omitted:

int mycolor = 0xff123456;    btn.setBackgroundColor(mycolor);  
4). Use the color defined by the system:

For example: BLACK, BLUE, CYAN, GRAY, GREEN, RED, WRITE ), YELLOW (YELLOW )!
Usage:Btn. setBackgroundColor (Color. BLUE );
You can also obtain the system color and then set it again:

int getcolor = Resources.getSystem().getColor(android.R.color.holo_green_light);  btn.setBackgroundColor(getcolor);  

Use in xml:Android: background = "@ android: color/black"

5). Use the static method argb to set the color:

Android uses an int type data to represent the color value, usually in hexadecimal format, that is, starting with 0x,
The color value is defined by the three primary colors of transparency alpha and RGB (red, green, and blue), starting with "#", followed:
Transparency-red-green-blue; Eg: # RGB # ARGB # RRGGBB # AARRGGBB
Each element is represented by one byte (8 bit), so the value range is 0 ~ 255. You can set colors in xml to ignore transparency,
However, if you are in Java code, you need to explicitly specify the transparency value. If you omit the value, it means completely transparent. At this time
No effect ~ For example, 0xFF0000 indicates red, but if you write something like this, you should write it like this:
0xFFFF0000, note the Java code to set the color value, you need to add transparency before ~
Example: (the parameters are transparency, red, green, and Blue values in sequence)
TxtShow. setBackgroundColor (Color. argb (0xff, 0x00, 0x00, 0x00 ));

2. NiewPatchDrawable

Figure. 9 is shown. In the previous tutorial on how to play the Android basic-1.6. 9 (jiumei) images
I 've explained how to create. 9 images! Android FrameWork uses efficient
Image optimization algorithms. We can achieve adaptive image stretching without special processing ~
Pay attention to the following points when using:

1. The figure at cannot be placed in the mipmap directory, but must be placed in the drawable directory! 2. The. 9 figure in AS must have a black line, otherwise the compilation will not pass. This morning, my cousin a said in the group
The artist of his company gave him a. 9 diagram without a black line, saying that he was made using a software and then on Eclipse.
Yes, it is not a black line. 9, slot, But I switched to the AS, directly compiling won't pass!
I think it's AS recognition. 9. The standard in the figure is to have a black shop or a black line! In addition, my cousin gave an example to remove the black line:
9 patch (. 9) how to remove the black spots/black lines drawn by yourself
I did not try it. If you are interested, you can try it on your own, but is the black line really eye-catching... I don't think I'm obsessive!
Another point is to decompress the apk of another user. When you take the. 9 clip, there is no black line, and an error will also be reported!
If you want to extract a. 9 clip with a black line, decompile the apk instead of decompressing it directly !!! Also before Decompilation
After introduction, we will not detail it here!

Next we will introduce two useless things:

Xml defines NinePatchDrawable:


    
    
    
    
  

Use Bitmap to wrap. 9 images:


    
    
    
  
3. ShapeDrawable

Shape Drawable, which defines the basic ry, such as (rectangle, circle, line, etc.). The root element is

4. GradientDrawable

A Drawable with gradient area can achieve linear gradient, divergence gradient and gradient effect
Core node: <Gradient/>, Which has the following optional attributes:

StartColor: The starting color of the gradient. CenterColor: Intermediate color of the gradient EndColor: Gradient end color Type: Gradient type, optional ( Linear, Radial, Sweep),
Linear Gradient(Gradient angle can be set), divergence gradient (center to around divergence), tile gradient CenterX: The x coordinate of Arthur in the middle of the gradient. value range: 0 ~ 1 CenterY: Y coordinate of the intermediate color of the gradient. value range: 0 ~ 1 Angle: The gradient is valid only for the linear type, indicating the gradient angle. It must be a multiple of 45. GradientRadius: Only radial and sweep gradient are valid. radial must be set to indicate the radius of the gradient effect. UseLevel: Determine whether or not to draw gradient effects based on level

Sample Code(Demonstration of three gradient effects ):

Run:

First, create three gradient xml files under drawable:

(Linear gradient) gradient_linear.xml:


  
      
       
    
   
  

(Divergence gradient) gradient_radial.xml:


  
      
   
    

(Tiled gradient) gradient_sweep.xml:


  
      
   
        

Call three drawableActivity_main.xml:


      
       
        
     
    
   
    

Okay, that's simple ~ Of course, if you want to draw more complex images, it is far from enough to use only xml files,
Java code is required for more complex results. The following shows a source code from the Internet:

Run:

Implementation Code:

MainActivity. java:

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(new SampleView(this));    }    private static class SampleView extends View {        private ShapeDrawable[] mDrawables;        private static Shader makeSweep() {            return new SweepGradient(150, 25,                    new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFF0000 },                    null);        }        private static Shader makeLinear() {            return new LinearGradient(0, 0, 50, 50,                    new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF },                    null, Shader.TileMode.MIRROR);        }        private static Shader makeTiling() {            int[] pixels = new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0};            Bitmap bm = Bitmap.createBitmap(pixels, 2, 2,                    Bitmap.Config.ARGB_8888);            return new BitmapShader(bm, Shader.TileMode.REPEAT,                    Shader.TileMode.REPEAT);        }        private static class MyShapeDrawable extends ShapeDrawable {            private Paint mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);            public MyShapeDrawable(Shape s) {                super(s);                mStrokePaint.setStyle(Paint.Style.STROKE);            }            public Paint getStrokePaint() {                return mStrokePaint;            }            @Override protected void onDraw(Shape s, Canvas c, Paint p) {                s.draw(c, p);                s.draw(c, mStrokePaint);            }        }        public SampleView(Context context) {            super(context);            setFocusable(true);            float[] outerR = new float[] { 12, 12, 12, 12, 0, 0, 0, 0 };            RectF inset = new RectF(6, 6, 6, 6);            float[] innerR = new float[] { 12, 12, 0, 0, 12, 12, 0, 0 };            Path path = new Path();            path.moveTo(50, 0);            path.lineTo(0, 50);            path.lineTo(50, 100);            path.lineTo(100, 50);            path.close();            mDrawables = new ShapeDrawable[7];            mDrawables[0] = new ShapeDrawable(new RectShape());            mDrawables[1] = new ShapeDrawable(new OvalShape());            mDrawables[2] = new ShapeDrawable(new RoundRectShape(outerR, null,                    null));            mDrawables[3] = new ShapeDrawable(new RoundRectShape(outerR, inset,                    null));            mDrawables[4] = new ShapeDrawable(new RoundRectShape(outerR, inset,                    innerR));            mDrawables[5] = new ShapeDrawable(new PathShape(path, 100, 100));            mDrawables[6] = new MyShapeDrawable(new ArcShape(45, -270));            mDrawables[0].getPaint().setColor(0xFFFF0000);            mDrawables[1].getPaint().setColor(0xFF00FF00);            mDrawables[2].getPaint().setColor(0xFF0000FF);            mDrawables[3].getPaint().setShader(makeSweep());            mDrawables[4].getPaint().setShader(makeLinear());            mDrawables[5].getPaint().setShader(makeTiling());            mDrawables[6].getPaint().setColor(0x88FF8844);            PathEffect pe = new DiscretePathEffect(10, 4);            PathEffect pe2 = new CornerPathEffect(4);            mDrawables[3].getPaint().setPathEffect(                    new ComposePathEffect(pe2, pe));            MyShapeDrawable msd = (MyShapeDrawable)mDrawables[6];            msd.getStrokePaint().setStrokeWidth(4);        }        @Override protected void onDraw(Canvas canvas) {            int x = 10;            int y = 10;            int width = 400;            int height = 100;            for (Drawable dr : mDrawables) {                dr.setBounds(x, y, x + width, y + height);                dr.draw(canvas);                y += height + 5;            }        }    }}

The Code uses ShapeDrawable and PathEffect. The former is the packaging of common images, including:
ArcShape, OvalShape, PathShape, RectShape, RoundRectShape!
While PathEffect is a path effect, including: CornerPathEffect, DashPathEffect and DiscretePathEffect
You can create complex graphic borders...
Here is the GradoemtDrawable gradient. If you are interested in the last thing, you can:
Appium/android-apidemos

 

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.