Drawing shape with Android custom view

summary

Previously, I wrote an article about the use of shape resources in drawable in Android. By defining the shape resources in drawable, I can draw simple graphic effects, such as rectangle, ellipse, line and ring. Later, I happened to encounter such a requirement in the project to display a vertical dotted line at a specific position. Just when I put the above resource file in, I found that it didn't meet my requirements. The vertical dotted line drawn by shape actually rotates a horizontal line by 90 degrees. However, the disadvantage of this is that the effective area of the view is the area that coincides with the original position after rotating 90 degrees, and can not be changed at will. This effect can not be used at all. So I thought of using a custom view to draw the results I want.

1. Draw a horizontal dotted line

The code is as follows:

The following are referenced in the layout file:

Note: in the code for customizing the view, the full name of the drawLine method executed in the OnDraw method is as follows:

public void drawLine (float startX,float startY,float stopX,float stopY,Paint paint)

Startx: start endpoint X coordinate starty: start endpoint y coordinate stopx: end endpoint X coordinate stopy: end endpoint y coordinate

The above four left values are calculated by relative position, that is, the relative position with the left control. If there is no control on the left, the relative position of the left border of the mobile phone screen is calculated. canvas.drawLine(0,mPaint); It indicates that starting from the position with X and Y coordinates of 0 on the left, draw a dotted line of 100px to the right.

After removing the button button, the relative position starts to be calculated based on the left border of the screen, as shown in the figure:

It should also be noted that the values of stopx and stopy cannot exceed the layout of the control in XML_ Width and layout_ The value of height, otherwise it will be based on the smallest value, and the exceeded length is invalid.

2. Draw a vertical dotted line

Consistent with the above code, it only needs to be modified to the following:

canvas.drawLine(0,mPaint);

3. Draw a solid circle

1) . first set the brush style to solid

mPaint.setStyle(Paint.Style.FILL); // Set brush style to fill

2) . draw a circle on the canvas

canvas.drawCircle(50,50,mPaint);

Similarly, the values of X and y cannot exceed the layout of the control in XML_ Width and layout_ The value of height.

4. Draw a circle

Again, just slightly modify the code:

5. Draw a rectangle

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>