Rating Bar

Discussion in 'iPhone/iPad Programming' started by chhoda, Nov 20, 2008.

  1. macrumors 6502

    Oct 25, 2008
    I am needed to show a rating bar where I can show movie ratings like 3 stars, 4 stars 3 and half stars. Is there a similar control available in iphone sdk ? Android seems to have one ... :)

  2. macrumors 65816

    Jun 29, 2007
    No but it would be hard to make. If I was asked to do this I would probably go this route:

    Subclass UIView
    In the drawrect area first fill a rect the percent of the "stars" So, if you have a total of 5 stars and the rating is 2 stars that would be 40% so fill the rect 40 of the total size. So, if your rect is 100px fill the color in only 40 percent.
    Once the rect is drawn simply put an image with transparent stars on top of it and the color will show through to the correct percentage.

    Even I'm confused with this but it makes sense to me, hope it helps.
  3. macrumors 6502a

    Oct 24, 2008
    There's no built-in control, but it's trivial to throw together a couple of UIImageViews to get the same effect.

    UIImage* star0 = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"star0" ofType:@"png"]];
    UIImage* star1 = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"star1" ofType:@"png"]];
    for (int i = 0; i < 5; i++) {
    	int xPos = star0.size.width * i;
    	int yPos = whatever;
    	if (i < rating) [self someDrawImageMethod:xPos :yPos :star1];
    	else [self someDrawImageMethod:xPos :yPos :star0];
    - (void)someDrawImageMethod:(int)xPos :(int)yPos :(UIImage *)image {
    	CGRect frame = CGRectMake(xPos, yPos, image.size.width, image.size.height);
    	UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    	imageView.image = image;
    	[self.view addSubview:imageView];
    // Release, etc.
    Extend for the case with half stars (i to 10, i % 2 == 1 to test for halves) and you're set.

    EDIT: detz's method is really nice too; cuts down on the number of images you create and handles floats rather than just ints.

Share This Page