Android drawing mechanism and processing skills

Posted by nite4000 on Mon, 04 May 2020 23:57:40 +0200

1 unit conversion

Due to the different screen density, the length of the same pixel size and the length displayed on the screen with different density are different. The following is the conversion formula of each density value,
In mdpi, 1dp = 1px,
In hdpi, 1dp = 1.5px,
In xhdpi, 1dp = 2px,
In the xxhdpi, 1dp = 3px,
The direct conversion formula is: ldpi:mdpi:hdpi:xhdpi:xxhpi = 3:4:6:8:12
The conversion code is as follows:

    /**
     * Change from dp unit to PX (pixel) according to the resolution of mobile phone 
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * Change from PX (pixel) to dp according to the resolution of mobile phone 
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     *  Use TypedValue provided by the system for conversion
     *  */
    public static int dp2px(Context context,float dp){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,context.getResources().getDisplayMetrics());
    }

    public static int px2dp(Context context,float px){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,px,context.getResources().getDisplayMetrics());
    }

2 drawing basis of 2D

The system provides drawing methods by providing Canvas objects, such as

       // Brush properties and corresponding functions 
        mPaint.setAlpha(8); //Set the Alpha of the brush
        mPaint.setStrokeWidth(5); //Set the width of the white border
        mPaint.setShader(new LinearGradient(0, 0, 400, 0, new int[]{Color.BLUE, 0x123321, Color.BLUE}, null, Shader.TileMode.CLAMP))
        mPaint.setTextSize(20);
        mPaint.setARGB(10,8,5,4); //Set the color value, respectively corresponding to the four channel components of transparency, red, green and blue to determine the color of pixel points
        mPaint.setAntiAlias(true);//Set the brush's zigzag effect
        mPaint.setColor(Color.YELLOW);//Set the color of the brush
        mPaint.setStyle(Paint.Style.STROKE);//Set the style of the brush: hollow STROKE or solid FILL
        Path path = new Path(); //Define a path 
        path.moveTo(40,50);//Move to coordinates 40 50
        path.lineTo(100,100);
        path.lineTo(100,50);
        path.lineTo(50,200);
       // Drawing functions and properties
        canvas.drawPath(path,mPaint);
        canvas.drawPosText("Hello",new float[]{
                100,100,//Coordinates of the first letter 
                100,200,//Coordinates of the second letter
                100,300,100,400,100,500},mPaint);//Draws text at the specified location
        canvas.drawOval(100,200,400,300,mPaint);//Draw ellipse
        RectF rect = new RectF(50, 50, 200, 200);//Define a rectangular area
        canvas.drawRoundRect(rect,
                30, //Radius of x-axis
                30, //Radius of y-axis
                mPaint);
        canvas.drawPoint(400,500,mPaint);//Draw points
        canvas.drawLine(200,300,500,600,mPaint);//Draw lines
        canvas.drawArc(rect1, //The size of the rectangular area used by the arc
                0,  //Start angle
                90, //Swept angle
                false, //Use center or not
                mPaint);
        canvas.drawText("android",200,410,mPaint);//Draw text
        canvas.drawRect(100,200,500,460,mPaint);//draw rectangle
        canvas.drawCircle(100,370,40,mPaint);//Draw a circle

3 XML drawing

3.1 Bitmap
You can create a Bitmap resource in the drawable / directory of XML. For example, you can create bit picture.xml in the drawable directory and implement the following code

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="drawable/drawable_resource"
    android:antialias=["true" | "false"]
    android:dither=["true" | "false"]
    android:filter=["true" | "false"]
    android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |
                      "fill_vertical" | "center_horizontal" | "fill_horizontal" |
                      "center" | "fill" | "clip_vertical" | "clip_horizontal"]
    android:mipMap=["true" | "false"]
    android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />

Through the above code, you can directly convert the image to Bitmap for direct use

    //xml call
    <ImageView
        android:layout_width="100dp"
        android:layout_weight="1"
        android:layout_height="100dp"
        android:src="@drawable/bit_picture"/>
    //Call in java
    getResources().getDrawable(R.drawable.bit_picture);

3.2 Shape
With shape, you can draw various shapes in XML. For example, under the res/drawable folder, create a new file named: shape_demo.xml code is as follows

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle"> // |oval|line|ring

    <!-- shape = rectangle Use when,The radius of the arc representing the corner is 1 by default dp-->
    <corners android:radius="9dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="2dp"
        android:bottomLeftRadius="3dp"
        android:bottomRightRadius="4dp"/>
    <!-- Solid fill -->
    <solid android:color="#00000000" />
    <!-- Stroke: 1 in general dp -->
    <stroke
        android:width="1dp"
        android:color="#ff000000"
        android:dashGap="15dp"
        android:dashWidth="40dp"/>
    <!-- Blank space around,and xml In the file pad Same effect, internal effect -->
    <padding
        android:bottom="30dp"
        android:left="20dp"
        android:right="30dp"
        android:top="20dp" />
    <!-- Specify size -->
    <size android:height="400dp"
        android:width="400dp"/>
    <!-- Background color gradient -->
    <gradient
        android:angle="45"
        android:endColor="#ff00ff00"
        android:startColor="#ff0000ff"
        android:type="linear"
        android:useLevel="true"
        android:centerColor="#611111"
        />
</shape>
//Call method is the same as 3.1

3.3 Layer
Layer is mainly used to achieve layer effect. For example, under res/drawable folder, create a new file named layer_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/arrow_right"/>
    <item android:left="10.0dip"
        android:top="10.0dip"
        android:right="20.0dip"
        android:bottom="30.0dip"
        android:drawable="@drawable/arrow_right"
        />
</layer-list>
//Call method is the same as 3.1

3.4 Selector
It mainly realizes event feedback in static drawing, sets different images through different events, and creates a new file under res/drawable folder, named as selector [demo.xml
Example 1

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Background picture by default-->
    <item android:drawable="@drawable/red"/>
    <!-- Background picture without focus-->
    <item android:state_window_focused="false"
        android:drawable="@drawable/dark_yellow"/>
    <!-- Background picture when focus is obtained and click in non touch mode-->
    <item android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/bule"/>
    <!-- Get focus in touch mode and click background picture-->
    <item android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/black"/>
    <!-- Background picture when selected-->
    <item android:state_selected="true"
        android:drawable="@drawable/dark_bule"/>
    <!-- Background picture when getting focus-->
    <item android:state_focused="true"
        android:drawable="@drawable/deep_yellow"/>
</selector>
// Call method is the same as 3.1

For example 2, use shape as its item in the Selector

    <item android:state_pressed="true" >
        <shape android:shape="rectangle">
            <solid android:color="#224444"></solid>
            <corners android:radius="5dp"/>
            <padding android:right="10dp"
                android:top="10dp"
                android:left="10dp"
                android:bottom="10dp"/>
        </shape>
    </item>
    <item >
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF"/>
            <corners android:radius="5dp"/>
            <padding android:bottom="10dp"
                android:top="10dp"
                android:left="10dp"
                android:right="10dp"/>
        </shape>
    </item>

4 drawing skills

Topics: Android xml encoding Mobile