Pages

Sunday 27 July 2014

ios: Rating Star


Introduction

This post contains a coding that describes the displaying of the static rating star. It is very simple but very effective.

Required Concept(s)
  1. CALayer
  2. UIView
Required Source(s)
  1. An Image with five stars like this




Source Code


 #define POINT             1.0
 #define WIDTH            82.5
 #define HEIGHT          15.0 
 #define DIVISOR         5.0 
 
 //Creation of Rating Star.

 CALayer *mainStar=[CALayer layer]; 
 mainStar.contents=(__bridge id)([UIImage imageNamed:@"rating_star"].CGImage);
 mainStar.frame=CGRectMake(POINT
,POINT,WIDTH,HEIGHT);
 CALayer *starColor=[CALayer layer];
 starColor.backgroundColor=[UIColor blueColor].CGColor;
 starColor.frame=
CGRectMake(0,0,
(3.5/DIVISOR)*WIDTH,HEIGHT);   
 //Change value of 3.5 from 0.0 to 5.0 to see the different rating.
[mainStar addSublayer:starColor];
CALayer *maskStar=[CALayer layer];
maskStar.contents=(__bridge id)([UIImage imageNamed:@"rating_star"].CGImage);
maskStar.frame=CGRectMake(0,0,WIDTH,HEIGHT);  
[mainStar addSublayer:maskStar];
 starColor.mask=maskStar; 
  
// Add Main Star to View
UIView *ratingView=[[UIView alloc] init];
ratingView.frame=CGRectMake(100,100,85,18);
[ratingView.layer addSubLayer:mainStar];
[self.view addSubView:ratingView];   // self may be any view controller.
  

Note
   Mask property of CALayer plays vital role.

Request
    Please post your comments and questions.


1 comment: