Easy Tutorial
❮ Verilog Basic Syntax Verilog Data Type ❯

8.1.1 Summary of 13 Drawable Types in Android Part 1

Category Android Basic Tutorial

Introduction:

>

Starting from this section, we will learn some basic knowledge of drawing and animation in Android, laying the foundation for our customizations in the advanced section! The first topic we will delve into is Drawable in Android! Android provides us with up to 13 types of Drawable, and in this section, we will go through each one!


Drawable Resource Usage Notes

>

Okay, these are the main points to pay attention to. Next, let's learn about the 13 types of Drawable provided by Android!


1. ColorDrawable

>

The simplest type of Drawable, when we draw a ColorDrawable onto the Canvas (canvas), it will fill the Paint with a fixed color, and then draw a single-color area onto the canvas!

1). Define ColorDrawable in Java:

ColorDrawable drawable = new ColorDrawable(0xffff2200);  
txtShow.setBackground(drawable);

2). Define ColorDrawable in xml:

<?xml version="1.0" encoding="utf-8"?>  
<color  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:color="#FF0000"/>

Of course, the above usages are not commonly used. More often, we create a color.xml file under the res/values directory and write the color values we need into it. When needed, we get the corresponding values through @color, for example:

3). Create a color.xml file

For example:

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <color name="material_grey_100">#fff5f5f5</color>
    <color name="material_grey_300">#ffe0e0e0</color>
    <color name="material_grey_50">#fffafafa</color>
    <color name="material_grey_600">#ff757575</color>
    <color name="material_grey_800">#ff424242</color>
    <color name="material_grey_850">#ff303030</color>
    <color name="material_grey_900">#ff212121</color>
</resources>

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

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

ps: Also, note that if we define the color value directly in Java, we need to add 0x, and we cannot omit the transparency:

int mycolor = 0xff123456;    
btn.setBackgroundColor(mycolor);

4). Use system-defined colors:

For example: BLACK (black), BLUE (blue), CYAN (cyan), GRAY (gray), GREEN (green), RED (red), WRITE (white), YELLOW (yellow)! Usage: btn.setBackgroundColor(Color.BLUE); You can also get the system color and then set it:

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

Usage 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, starting with 0x. The color value is defined by the transparency alpha and the three primary colors RGB (red, green, blue), starting with "#", followed by: transparency-red-green-blue; eg: #RGB #ARGB #RRGGBB #AARRGGBB txtShow.setBackgroundColor(Color.argb(0xff, 0x00, 0x00, 0x00));


2. NinePatchDrawable

>

It's the .9 image. In the previous section 1.6 How to Use .9 (Nine-Sister) Images, we have explained in detail how to create .9 images! The Android Framework uses an efficient graphics optimization algorithm when displaying .9 images, and we don't need special handling to achieve adaptive image stretching. Also, note the following when using AS:

Next, let's introduce two things that are not very useful:

Define NinePatchDrawable in xml:

<!--pic9.xml-->  
<!--Parameters are: referenced .9 image, whether to dither the bitmap-->  
<?xml version="1.0" encoding="utf-8"?>  
&lt;nine-patch  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:src="@drawable/dule_pic"  
    android:dither="true"/>

Use Bitmap to wrap .9 image:

<!--pic9.xml-->  
<!--Parameters are: referenced .9 image, whether to dither the bitmap-->  
<?xml version="1.0" encoding="utf-8"?>  
<bitmap  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:src="@drawable/dule_pic"  
    android:dither="true"/>

3. ShapeDrawable

>

A Drawable of shape, defining basic geometric shapes, such as (rectangle, circle, line, etc.), the root element is <shape../> There are many related nodes, as follows:

Usage example: 2.3.1 TextView (Text Box) Detailed Explanation


4. GradientDrawable

>

A Drawable with a gradient area, which can achieve linear gradient, radial gradient, and tiled gradient effects Core node: <gradient />, with the following optional attributes:

Code Example: (Demonstration of three gradient effects):

Runtime Effect Diagram:

First, create three gradient XML files under drawable:

(Linear Gradient) gradient_linear.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >
    <gradient
        android:angle="90"
        android:centerColor="#FFEB82"
        android:endColor="#35B2DE"
        android:startColor="#DEACAB" />

    <stroke
        android:dashGap="5dip"
        android:dashWidth="4dip"
        android:width="3dip"
        android:color="#fff" />
</shape>

(Radial Gradient) gradient_radial.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadius="0dip"
    android:shape="ring"
    android:thickness="70dip"
    android:useLevel="false" >

    <gradient
        android:centerColor="#FFEB82"
        android:endColor="#35B2DE"
        android:gradientRadius="70"
        android:startColor="#DEACAB"
        android:type="radial"
        android:useLevel="false" />

</shape>

(Sweep Gradient) gradient_sweep.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadiusRatio="8"
    android:shape="ring"
    android:thicknessRatio="3"
    android:useLevel="false" >

    <gradient
        android:centerColor="#FFEB82"
        android:endColor="#35B2DE"
        android:startColor="#DEACAB"
        android:type="sweep"
        android:useLevel="false" />

</shape>

Calling the three drawables in activity_main.xml:

<LinearLayout 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"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txtShow1"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:background="@drawable/gradient_linear" />

    <TextView
        android:id="@+id/txtShow2"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/gradient_radial" />

    <TextView
        android:id="@+id/txtShow3"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/gradient_sweep" />

</LinearLayout>

That's it, quite simple! Of course, if you want to draw more complex shapes, XML files alone are not enough. More complex effects require Java code to achieve. Below is a source code example from the web:

Runtime Effect Diagram:

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;
            }
        }
    }
}

Follow on WeChat

❮ Verilog Basic Syntax Verilog Data Type ❯