Android custom star scoring control

The following is the implementation process of the control: this control is efficient and can be drawn directly using OnDraw. Light it first:

Because Android's own star scoring control style can be changed, but its size is not easy to adjust, it can only be adjusted with a style such as small normal, and the customization is not strong, so it triggered my desire to customize the star control.

The design of star scoring control is generally planned as follows:

Need two pictures, a bright star and an empty star; (of course, the pictures are not necessarily stars, and other pictures are OK. Just use stars in the experiment now.) the number and spacing of stars can be customized. The minimum step of stars is 0.1, which is the same as the method provided by Android when used by users.

The star control is generally divided into two layers: the first layer is empty stars, the second layer is bright stars, the first layer is fixed, and the second layer is dynamically drawn, so that scoring can be realized.

When drawing stars, because the object obtained in XML is drawable, it does not need to be converted to bitmap drawing, so draw drawable directly and improve efficiency.

Two methods are enough to draw drawable. 1. Set where to draw: setbounds (int left, int top, int right, int bottom); 2. Drawing: draw (canvas);

After a for cycle, five empty stars come out, ha ha

The above lines of code were successfully forced into a 4-point rating

Now, there is no pressure to show a few stars, but our goal is to need a star with a step of 0.1. But after a series of experiments, it was found that the drawable object could not specify the part needed for drawing, that is, it could not draw half a star (anyway, if you can't find it, you can comment and tell me). Then, it adopted a compromise method to change the drawable object into bitmap, which is easy to do. Then, it used bitmapshader to draw as many as you want (that is, 0.1 step), The following is the effect of 1 / 3 pills:

Conversion method:

Convert bitmap to brush drawing:

Draw (one third) in the OnDraw () method

canvas.drawRect(0,starSize/3,paint);

This is the principle. The rest is the logic problem. The following is the star control code:

Attrs file:

How to use XML:

< key > project source code: http://xiazai.jb51.net/201701/yuanma/AndroidStarBar (jb51.net).rar

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
分享
二维码
< <上一篇
下一篇>>