Android Custom scoring controls: Ratingstarview

Source: Internet
Author: User

Android custom scoring controls, like Ratingbar, use the star icon (full, half, empty) as the "scoring/scoring control" for the rating value.

Figure 1:
Features supported by the Ratingstarview control:

    • Half-Star support (actual support for any decimal number)
    • Fill color, background, stroke color
    • Specify height, Width adaptive
    • Corner radian, stroke width, star spacing
    • Obesity index (star thickness), the fatter the more lovely
    • Click to score (half star not supported)
Implementation ideas

The following is the implementation design of Ratingstarview.

How to draw a star star standard coordinates

The "standard coordinates"of a star can be computed in an abstract Xoy coordinate system. This coordinate can be used as a benchmark for subsequent calculation of coordinates (offset and scale).
Figure 2:

Take the diagram above as an example, where the center point O is the origin point.
For the convenience of description, the a,b,c,d,e is called 5 outer points (Outer Corner Vertex), a,b,c,d,e Five points are interior points (Inner Corner Vertex).

Here the coordinates of the selection is entirely for the sake of calculation convenience to consider, after all, we can choose other coordinate mode, such as the location of the Origin o in other places, or the range of stars from the height, width and so on.

5 outer vertices

The coordinates of a inflection point are (0,1), and the coordinates of several other points can be fixed according to the geometric formula. To simplify calculations, you can save these values as constants, and then calculate the other values based on them. The following code is for the convenience of the program e-point coordinates x, y values are the starting elements :

private  Static final float[] starvertexes = new float[]{-0.9511f, 0.3090f, //E (left) 0.0000f, 1.0000f, //A (top vertex) 0.9511f, 0.3090f, //B (right) 0.5878f, -0.8090f, //C (bottom right) -0.5878f, -0.8090f, //D (bottom left)};        

Use constants to simplify the Cos and sin operations when calculating pentagram coordinates. Because the coordinates of these points are fixed in geometry. The coordinate system can then be transformed by a simple +-*/operation, as well as the star size.
Constants are not kept too much, such as A,b,c,d,e's calculations are based on a,b,c,d,e.

5 Internal inflection points

Here, star thickness is used to control the loveliness of the Stars by introducing the word "weight factor (Star)".
Obviously, the weight of the a,b,c,d,e is determined by the position of the five inner points.
But in terms of computation, here's another way:

Set the variable thickness to represent the obesity factor, and the position of the 5 inner points is calculated from the Origin o and the two outer points near the inner point.

Or the above Figure 2,
The midpoint of AE is P, so e must be on the OP, and if you take other points on the OP, as the EPA such a polygon path (the other five inner points similar) can create a different fat stars.

Here because the Origin O is the center of the stars, in the standard coordinate system , according to the fat coefficient thickness, combined with ABCDE these points, you can calculate the ABCDE these points, and when the thickness different, the star fat difference.

The process of calculating ABCDE according to thickness and ABCDE must be in the "standard coordinate system", that is, the x+ axis to the right, y+ upward, and O origin is the Star center!!

Coordinate transformation

Each star to be displayed is represented by a StarModel class that holds the coordinate information of a star and completes the corresponding calculation.
Its code is the entire ratingstarview about the coordinates part of the core, complete code see the following source address.

Inflection point (vertex) represents

The vertex of the star can be represented by a pointf, but here, to facilitate the use of multiple points as a linked list, defines the following VertexF to hold the vertex data:

class VertexF {    public VertexF() { } public VertexF(float x, float y) { this.x = x; this.y = y; } public float x; public float y; public VertexF next;}
Calculation of 10 inflection points

The Starmodel class uses a static array to hold the coordinate initial values of the standard coordinate system ABCDE the five outer points.

Since the thickness coefficients must be computed in a standard coordinate system, the Starmodel constructor is chosen to accept the thickness parameter, and all 10 inflection points are computed in the initialization.

Convert to Android coordinate system

Under Mobile devices, Android y+ is down, so a adjustcoordinate () method is required to complete the conversion of the star coordinate system.
It also turns the star's X, Y to positive-so it's visible.

Note in Android, when Childview draws its own content, it uses the x, y coordinate units of pixel, and is relative to the relative coordinates of its parent viewgroup.

Offset and scale

Ratingstarview when displaying several star, you need to be able to control its position and size.
So Starmodel will also need to be offset and scaled after the standard coordinate system has been converted to Android under the coordinate system (relative coordinates in the parent layout).

Offset

Only 10 inflection point coordinates must be +,-operate.

The size of the star is measured here using height, because the drawing is definitely the complete star, so that height and width are proportional. Choosing height or width as its size can be measured by itself.

Scaling

First, as measured by the height of the star, the star is assumed to have a default scaling factor after the conversion in the standard coordinate system: it is the vertical distance of its height ad (or AC) segment.

Then to set a new height for the star (that is, to change its size range-the external rectangle border Outerrect), according to the height of the change of the multiplication operation can be-pay attention to the coordinate problem, this is left to write code thinking. :)

Custom View implementations

The above is a calculation of coordinates and coordinates, mainly done by the StarModel class, which holds the data for each star to be displayed.

The function of drawing is implemented by Ratingstarview, which inherits the view class:

class RatingStarView extends View;
View size Measurement

The first step in customizing the control is to solve the measurement problem of its own size.
The size of the star is determined by its height, as mentioned earlier.

In order to display multiple star at the same time, and considering the features declared at the beginning of the article, the logic of how to measure the size of Ratingstarview is determined.

It is important to note that the general guidelines for view measurements are to be followed: match_parent Such an unqualified case-the height is also prioritized at this time.

In Onmeasure ():

@OverrideProtectedvoidOnmeasure(int Widthmeasurespec,int Heightmeasurespec) {int widthmode = Measurespec.getmode (Widthmeasurespec);int heightmode = Measurespec.getmode (Heightmeasurespec);int widthsize = measurespec.getsize (Widthmeasurespec);int heightsize = measurespec.getsize (Heightmeasurespec);float width;int height;Must has heightif (Heightmode = = measurespec.exactly) {height = heightsize;}else {height = default_star_height;if (Heightmode = = measurespec.at_most) {height = math.min (height, heightsize);}}float starheight = Height-getpaddingbottom ()-getpaddingtop ();if (Widthmode = measurespec.exactly) {//Parent have told us how B IG to be. So is it. width = widthsize; } else {//get the perfect width width = getpaddingleft () + Getpadd Ingright (); if (Starnum > 0) {if (starHeight > 0) {width + = Starmargin * (Starnum-1); width + = Starmodel.gets Tarwidth (starheight) * starnum; }} if (Widthmode = measurespec.at_most) {width = math.min (widthsize, width);}} int widthint = (int) (width); if (Widthint < width) {widthint++;} setmeasureddimension (Widthint, height);}  

The principle of calculation is to first determine the height of the view, as the altitude of the star.
Consider Padding,starmargin (star spacing).
Because it is a float value-related calculation, the final size of the measurement should take an "upward" integer.

Layout

Ratingstarview is not a viewgroup, it does not require layout childview.
However, you need to determine the coordinate data of each star to be displayed according to its size.

Listen for the view size change in onsizechanged () and calculate the Star (multiple) coordinate data to be displayed, that is private ArrayList<StarModel> starList :

@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (h != oldh) { calcStars(); }}
/** * Create All Stars data, according to the Contentwidth/contentheight. */PrivatevoidCalcstars() {int paddingleft = Getpaddingleft ();int paddingtop = Getpaddingtop ();int paddingright = Getpaddingright ();int paddingbottom = Getpaddingbottom ();int contentwidth = getwidth ()-paddingleft-paddingright;int contentheight = GetHeight ()-paddingtop-paddingbottom;int left = Paddingleft;int top = paddingtop;According to the View's height, make star height.int starheight = Contentheight;if (Contentheight > Contentwidth) {starheight = Contentwidth;}if (Starheight <=0) return; float startwidth = starmodel.getstarwidth (starheight); //Starcount * startwidth + (starCount-1) * Starmargin = contentwidth int starcount = (int) ((Contentwidth + Starmargin)/(Startwidth + starmargin)); if (Starcount > Starnum) {starcount = Starnum;} starlist = new arraylist<> (Starcount); For (int i = 0; i < Starcount; i++) {Starmodel star = new Starmodel (starthicknessfactor); starlist.a DD (STAR); Star.setdrawingouterrect (left, top, starheight); Left + = Startwidth + 0.5f + starmargin;} ...}            
Draw a Pentagram

Canvas.drawPath()Can be used to draw a closed path consisting of several points.

Method Prototypes:

/** * Draw the specified path using the specified paint. The path will be * filled or framed based on the Style in the paint. * * @param path  The path to be drawn * @param paint The paint used to draw the path */public void drawPath(@NonNull Path path, @NonNull Paint paint)

But in order to draw "rounded pentagram", you need to set the paint's "path effect":

Set or clear the patheffect object. * <p /> * Pass null to clear any previous patheffect. * As a convenience, the parameter passed is also returned. * * @param effect May be null. The patheffect to be installed in the paint * @return effect */public PathEffect setPathEffect(PathEffect effect)

You can set it here public class CornerPathEffect extends PathEffect .

Mars and the Empty star

Paint can set its style.
Fullstar:Paint.Style.FILL_AND_STROKE
Emptystar:Paint.Style.STROKE

Half Star

Canvas supports layer operations.
You can draw empty stars on the first layer.
Then draw a full star in the new layer-and use it canvas.clipRect(clip); to crop half the stars. Because
Cliprect is a rectangle, so you can actually draw any decimal star--only 0.5 (half star) is the best.

Property and Attributes

Good controls need to support all aspects of creating and setting up Java code and XML.
Ratingstarview Support:

    • Set the number of star
    • Set Rating (float value, one star do 1 regards)
    • Set thickness
    • Other spacing, size, width, color, etc.

It's open source, and you can modify and expand it yourself.

Event

Ratingstarview Support click-to-score, does not support half-star-half-star This is a lot of user ratings after the mean.

Record the x, y coordinates of the Click in Ontouchevent ():

@Overridepublic boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { clickedX = event.getX(); clickedY = event.getY(); } return super.onTouchEvent(event);}

Ratingstarview self-Realization View.onclicklistener, listen to their own click.
The rating is changed in the onclick () callback based on the displayed starlist, as well as its size.

By default it is used only to show ratings (read-only), and click Ratings can be turned on by enableselectrating properties.

Fast use of Gradle dependencies

See here
"https://jitpack.io/#everhad/androidratingstar/v1.0.1".

Add the Jitpack repository to your build file
allprojects {    repositories {        ...        maven { url ‘https://jitpack.io‘ }    }}
Add the dependency
dependencies {    compile ‘com.github.everhad:AndroidRatingStar:v1.0.1‘}
In the ' Layout.xml '
<Com.idlestar.ratingstar.RatingStarViewapp:cornerradius="4DP"app:starmargin="12DP"App:strokewidth="2PX"App:strokecolor="#457DD7"App:starforegroundcolor="#DB6958"App:starbackgroundcolor="#E8E8E8"app:starnum="5"app:rating="1"app:enableselectrating="true" app:starthickness= "0.7" android:layout_margintop="8DP" app:drawstrokeforemptystar= "false" app:drawstrokeforhalfstar="true" android:paddingtop="2DP" android:paddingleft= "0DP" android:paddingright= "0dp" android:background="#fff" android:layout_width= "Wrap_content" android:layout_height="40DP"/>         
In the Java code
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RatingStarView rsv_rating = (RatingStarView) findViewById(R.id.rsv_rating); rsv_rating.setRating(1.5f);}
Source

The complete code is shown here:
Https://github.com/everhad/AndroidRatingStar

Hopefully it will save you time (go and UI to various icon custom Ratingbar)

Android Custom scoring controls: Ratingstarview

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.