Question

I create the following View in code, the idea is to use it as an image in UITableViewCell and UITabBarItem:

- (void)drawRect:(CGRect)rect
{
    // Fill the background with white
    CGContextRef context = UIGraphicsGetCurrentContext();

    UIColor * whiteColor = [UIColor colorWithRed:1.0
                                           green:1.0
                                            blue:1.0
                                           alpha:1.0];

    CGContextSetFillColorWithColor(context, whiteColor.CGColor);
    CGContextFillRect(context, self.bounds);

    //// Color Declarations
    UIColor* fillColor = [UIColor colorWithRed: 1.0
                                         green: 1.0
                                          blue: 1.0
                                         alpha: 1.0];

    UIColor* strokeColor = [UIColor colorWithRed: 0.0
                                           green: 0.0
                                            blue: 0.0
                                           alpha: 1.0];

    //// Big Oval Drawing
    CGRect bigOvalRect = CGRectMake(rect.origin.x+2,
                                    rect.origin.y+5,
                                    42.0,
                                    42.0);

    UIBezierPath* bigOvalPath = [UIBezierPath bezierPath];

    [bigOvalPath addArcWithCenter: CGPointMake(CGRectGetMidX(bigOvalRect), CGRectGetMidY(bigOvalRect))
                         radius: CGRectGetWidth(bigOvalRect) / 2
                     startAngle: 40 * M_PI/180
                       endAngle: 320 * M_PI/180
                      clockwise: YES];

    [fillColor setFill];
    [bigOvalPath fill];
    [strokeColor setStroke];
    bigOvalPath.lineWidth = 1;
    [bigOvalPath stroke];

 }

To create an UIImage from this UIView I am using this code:

#import <QuartzCore/QuartzCore.h>

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

Everything works as expected when I use it in my UITableViewCells but when I set it as the image of my UITabBarItem I only see a blue rectangle (iOS7):

MyIcon *icon = [[MyIcon alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
UIImage *tabImage =[self imageWithView:icon];

self.navigationController.tabBarItem.image = tabImage;

I guess it is something related with the alpha of the image but how can I fix it?

Was it helpful?

Solution

It wasn't a problem related to the size of the view but to its alpha.

I fixed it by setting the backgroundColor (was whiteColor) and the fillColor to:

[UIColor clearColor]

and by setting the view as opaque in the initWithFrame: method:

[self setOpaque = NO];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top