I have a custom table view cell that is intended to draw a circle like the iPhone’s Mail.app does:
Instead, it draws like this:
Here’s my code:
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *grayColor = [UIColor grayColor];
[grayColor set];
CGContextStrokeEllipseInRect(context, CGRectMake(9, 10, 23, 23));
How can I make it not suck? :)
Edit: Ignore the fact that I omitted the code that draws the white background color.
What about it sucks? It doesn’t look close to, if not exactly like, the circle from Mail.
I was able to solve this by changing the UIColor to the same color Apple uses, #E5E5E5:
[UIColor colorWithRed: 0.8980392157 green: 0.8980392157 blue: 0.8980392157 alpha: 1.0]
And changing the line width from the default 1.0 to 2.0:
CGContextSetLineWidth(context, 2.0);
Tweaking the size was also necessary:
CGContextStrokeEllipseInRect(context, CGRectMake(10, 11, 21, 21));
The final code looks like this:
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *grayColor = [UIColor colorWithRed: 0.8980392157 green: 0.8980392157 blue: 0.8980392157 alpha: 1.0];
[grayColor set];
CGContextSetLineWidth(context, 2.0);
CGContextStrokeEllipseInRect(context, CGRectMake(10, 11, 21, 21));
And outputs like this:
Try setting its alpha to 0.5 and making the borders thicker, for example, like this:
CGContextSetAlpha(context, 0.5);
Related
I've been trying to replicate the gradient from UINavigationBar to use as a gradient on custom UIButton subclass objects on the same view.
However, I can't figure out how the colors are derived? That is, you only specify one color to set a UINavigationBar's background color- tintColor - but it creates a nice gradient with it seems at least 4 colors?
I'm really just interested in the "inner" top and bottom colors though - just inside the 1px border around the bar... the outer "border" colors do indeed appear different though.
EDIT - 1
Upon further research, it appears the HSB (instead of the RBG as first thought) values are being manipulated to get these different colors.
There is also a convenience method on UIColor to get the HSB values, which should be helpful:
getHue:saturation:brightness:alpha:
Helpful References Found So Far
HSL and HSV Wiki
UIColor Class Reference
Programmatically Lighten a Color
From the book Fundamentals of Interactive Computer Graphics
EDIT - 2
In case you were unaware that you could set a gradient for a background on a UIButton programmatically, here's some references for how to do such:
FUN WITH UIBUTTONS AND CORE ANIMATION LAYERS
Five Tips for Creating Stylish UIButtons (kudos to #cdo for providing this link)
EDIT - 3
I've put together a spreadsheet showing the original and the "inner" gradient colors (disregarding the outer most colors) in HSB values on UINavigationBar and its corresponding "back" button (titles are irrelevant and always displayed white).
Here's a link to the Google doc with the information that I've collected for a few sample colors:
https://docs.google.com/spreadsheet/ccc?key=0AnKVtzkNS9scdGVRN01pa1NQcC1hdThNbEVzQU8wRlE&usp=sharing
Note: these values were found by saving a screenshot using the retina, 3.5" iPhone Simulator (Xcode version 4.6) for iOS 6.1 and eye-dropping the HSB values using PhotoShop.
BOUNTY AWARD CRITERIA
I've opened a bounty on this question to bring more exposure to it and hopefully get a good answer. The answer that I'm looking for:
Provide a method of calculating/closely approximating (in most cases) the RGB or HSB values of the "inner top" and "inner bottom" gradient colors (see spreadsheet) created after setting a tintColor on UINavigationBar.
Bonus points awarded (above initial bounty offering) if you also provide a method for calculating the "inner top" and "inner bottom" gradient colors on the "back" button (which is similar to the navigation bar, but I've found these colors appear to be slightly "darker" usually)?
Short Answer: it is not gradient
Long Answer: After tint color applied, there is a transparent overlay image rendered on top of it.
It is called: UITintedTopBarHighlight#2x.png an it is in UIKit artwork. (uploaded here: http://cl.ly/image/2c2V3t1D1T3L)
It is 2x88 pixel image, and must be repeated horizontally over tinted background.
For back button, it is very similar, but there is also a mask to give it it's shape. UItintedBackButtonHighlight and UITintedBackButtonMask.
It's hard to copy the exact behavior because it seems that Apple is calculating different for different color groups. eg. a light color is slightly darkened while a dark color is lit up.
Same for the bar button item. For some colors the difference for normal "bordered" button and "done"-style button is completely different. Sometimes not noticeable like for turquoise but definitely seeable for orange.
For creating this sample code I used PaintCode a nice tool for prototyping btw..
Copy this code in a UIView subclass or something. Or just grab the pieces code you need.
- (void)drawRect:(CGRect)rect
{
//// General Declarations
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();
//// Color Declarations
UIColor* tint = [UIColor colorWithRed: 1 green: 0.66 blue: 0.329 alpha: 1];
CGFloat tintRGBA[4];
[tint getRed: &tintRGBA[0] green: &tintRGBA[1] blue: &tintRGBA[2] alpha: &tintRGBA[3]];
UIColor* lighter = [UIColor colorWithRed: (tintRGBA[0] * 0.58 + 0.42) green: (tintRGBA[1] * 0.58 + 0.42) blue: (tintRGBA[2] * 0.58 + 0.42) alpha: (tintRGBA[3] * 0.58 + 0.42)];
CGFloat lighterRGBA[4];
[lighter getRed: &lighterRGBA[0] green: &lighterRGBA[1] blue: &lighterRGBA[2] alpha: &lighterRGBA[3]];
UIColor* lightest = [UIColor colorWithRed: (lighterRGBA[0] * 0.55 + 0.45) green: (lighterRGBA[1] * 0.55 + 0.45) blue: (lighterRGBA[2] * 0.55 + 0.45) alpha: (lighterRGBA[3] * 0.55 + 0.45)];
UIColor* darker = [UIColor colorWithRed: (tintRGBA[0] * 0.92) green: (tintRGBA[1] * 0.92) blue: (tintRGBA[2] * 0.92) alpha: (tintRGBA[3] * 0.92 + 0.08)];
CGFloat darkerRGBA[4];
[darker getRed: &darkerRGBA[0] green: &darkerRGBA[1] blue: &darkerRGBA[2] alpha: &darkerRGBA[3]];
UIColor* darkest = [UIColor colorWithRed: (darkerRGBA[0] * 0.65) green: (darkerRGBA[1] * 0.65) blue: (darkerRGBA[2] * 0.65) alpha: (darkerRGBA[3] * 0.65 + 0.35)];
//// Gradient Declarations
NSArray* gradientColors = [NSArray arrayWithObjects:
(id)lighter.CGColor,
(id)darker.CGColor, nil];
CGFloat gradientLocations[] = {0, 1};
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocations);
//// top Drawing
UIBezierPath* topPath = [UIBezierPath bezierPathWithRect: CGRectMake(0, 0, rect.size.width, 1)];
[lightest setFill];
[topPath fill];
//// theGradient Drawing
UIBezierPath* theGradientPath = [UIBezierPath bezierPathWithRect: CGRectMake(0, 1, rect.size.width, rect.size.height - 1.0f)];
CGContextSaveGState(context);
[theGradientPath addClip];
CGContextDrawLinearGradient(context, gradient, CGPointMake(50, 1), CGPointMake(50, rect.size.height-1.0f), 0);
CGContextRestoreGState(context);
//// bottom Drawing
UIBezierPath* bottomPath = [UIBezierPath bezierPathWithRect: CGRectMake(0, rect.size.height-1.0f, rect.size.width, 1)];
[darkest setFill];
[bottomPath fill];
//// Cleanup
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
Thanks for the good question and the generous bounty. I went to work on this and neglected to check in to see that it was already answered acceptably. Nevertheless, it was fun building and testing the following navigation bar category, that reveals it's colors ...
//
// UINavigationBar+colors.h
#import <UIKit/UIKit.h>
#interface UINavigationBar (Colors)
// Answer an array of colors representing the color of the reciever, starting at fromY, up to toY
- (NSArray *)colorsFromY:(NSUInteger)fromY to:(NSUInteger)toY;
#end
Link with QuartzCore.framework.
//
// UINavigationBar+colors.m
#import "UINavigationBar+colors.h"
#import <QuartzCore/QuartzCore.h>
#define UIIMAGE_BYTES_PER_PIXEL 4u
#implementation UINavigationBar (Colors)
+ (NSData *)dataFromImage:(UIImage *)image {
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger dataSize = height * width * UIIMAGE_BYTES_PER_PIXEL;
unsigned char *rawData = malloc(dataSize);
NSUInteger bytesPerRow = width * UIIMAGE_BYTES_PER_PIXEL;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
NSData *rtn = [NSData dataWithBytes:rawData length:dataSize];
free(rawData);
return rtn;
}
+ (UIColor *)colorOfImage:(UIImage *)image atX:(NSUInteger)px atY:(NSUInteger)py {
NSData *imgData = [self dataFromImage:image];
if (!imgData) return nil;
NSUInteger byteIndex = UIIMAGE_BYTES_PER_PIXEL * (image.size.width * py + px);
unsigned char rgbaData[4];
NSRange range = { byteIndex, 4u };
[imgData getBytes:rgbaData range:range];
CGFloat red = rgbaData[0] / 255.0;
CGFloat green = rgbaData[1] / 255.0;
CGFloat blue = rgbaData[2] / 255.0;
CGFloat alpha = rgbaData[3] / 255.0;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
- (UIImage *)asImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
- (NSArray *)colorsFromY:(NSUInteger)fromY to:(NSUInteger)toY {
NSMutableArray *answer = [NSMutableArray array];
UIImage *image = [self asImage];
for (NSUInteger y = MAX(0, fromY); y < MIN(self.bounds.size.height, toY); y++) {
[answer addObject:[self.class colorOfImage:image atX:1 atY:y]];
}
return [NSArray arrayWithArray:answer];
}
#end
Call it like this:
// from a view controller contained by a navigation controller...
UINavigationBar *bar = self.navigationController.navigationBar;
NSArray *colors = [bar colorsFromY:0 to:bar.bounds.size.height];
for (UIColor *color in colors) {
NSLog(#"%#", color);
}
UIButton takes a single tintColor property but that doesn't mean it isn't computing other colors to use in the gradient behind the scenes. Try this tutorial.
I am following Brad's answer to apply glow effect in my CALayer text.
Here is my code:
- (void)drawLayer:(CALayer *)theLayer inContext:(CGContextRef)context
{
UIGraphicsPushContext(context);
UIFont *font = [UIFont fontWithName:#"Verdana" size:11.0f];
CGRect rect = CGRectMake(theLayer.bounds.origin.x + 5, theLayer.bounds.origin.y + 5, theLayer.bounds.size.width - 10, theLayer.bounds.size.height - 10);
NSString * textToWrite = #"Some text";
UIColor *color = [ UIColor colorWithRed: (100.0f) green: (50.0) blue:(200.0f) alpha: 1.0f ];
CGContextSetFillColorWithColor(context, color.CGColor); //this has no effect!!!
CGContextSetShadowWithColor(context, CGSizeMake(0.0, 0.0), 2.0f, [UIColor greenColor].CGColor);
[textToWrite drawInRect:rect withFont:font
lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
UIGraphicsPopContext();
}
I am getting a decent green glow here. However I want the text to have its own color too, apart from glow. For this I am using color variable here, along with CGContextSetFillColorWithColor. But it seems to have NO effect. The text seems white, with green glow. I want text with main color = color and glow=green.
What should I do?
I'm confused by your color... I think when declaring red green and blue in objective-c you set values that are up to 1.0 being the maximum (like you did with alpha) so when you give them their true 255 hex value you then divide by 255. Your color should be white since all 3 values are so far above the maximum... Maybe I'm wrong though first try these two codes...
Replace your current FillColorWithColor code with this:
[[UIColor colorWithCGColor:color] set];
(or maybe this...)
[[UIColor colorWithCGColor:color.CGColor] set];
If they don't work then try them while also changing your color code to this:
UIColor *color = [ UIColor colorWithRed: (100.0f/255.0f) green: (50.0f/255.0f) blue:(200.0f/255.0f) alpha: 1.0f ];
I did the following :
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
UIGraphicsPushContext ( ctx );
CGRect r = CGRectMake( 500, 300, 200, 100 );
NSString *text = [[NSString alloc] initWithString:#"raaaaaaaa!"];
UIColor *color = [ UIColor colorWithRed: (200.0f) green: (100.0) blue:(200.0f) alpha: 1.0f ];
[color set];
[ text drawInRect: r withFont:[UIFont systemFontOfSize:50] lineBreakMode: UILineBreakModeWordWrap alignment: UITextAlignmentLeft ];
[text release];
UIGraphicsPopContext();
}
}
}
The above code is not working. Why?
If i do the following instead, it is working:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
UIGraphicsPushContext ( ctx );
CATextLayer *label = [[CATextLayer alloc] init];
[label setFont:#"Didot"];
[label setFontSize:50];
[label setFrame:CGRectMake( 400, 300, 400, 100 )];
[label setString:#"Helloooooooooooooooooo"];
[label setAlignmentMode:kCAAlignmentCenter];
[label setForegroundColor:[[UIColor blueColor] CGColor]];
[layer addSublayer:label];
[label release];
UIGraphicsPopContext();
}
}
What is the difference and why drawInRect does nothing?
Thank you
EDIT
So, I was not using UIColor properly, so I changed
UIColor *color = [ UIColor colorWithRed: (200.0f) green: (100.0) blue:(200.0f) alpha: 1.0f ];
for this
UIColor *color = [UIColor colorWithRed:200 / 255.0 green:100 / 255.0 blue: 200 / 255.0 alpha: 1.0];
Still no luck, I can't see any text when using drawInRect
There are two questions in you question:
The above code is not working. Why?
At first I thought that the text didn't show up because it was drawn with white on white. While it may still have been so, that is not the only problem.
The rectangle that you are drawing your text into (r) is relative to the bounds of the layer you are drawing in. I.e. if you want to draw in the top left corner of the layer, the origin of the rect should be (0, 0). The above code is still not working though.
If you inspect the CGSize that drawInRect:withFont:... returns (the size of the rendered text) you can see that the size of the rendered text is 0 wide. This is an indication that the height of 100 for the rectangle to draw in is not enough. Increasing the height of the rectangle solves this and now the text is visible. If you are drawing some text inside a layer, maybe the most sensible rectangle to draw in is the bounds of the layer (CGRect r = [layer bounds];).
What I did to make it work:
Changed text color
Changed origin of r to (0,0)
Increased height of r
What is the difference [...] ?
In the first you are drawing text into the graphics context of the layer (what drawLayer:inContext: is supposed to do) but in the seconds example you are adding another layer to the hierarchy of the layer instead of drawing inside it. Every time your layer will redraw, a new text layer will be added to it. So nothing is actually drawn into the layers graphics context.
What happens next, after your layer has drawn itself (empty), is that the sublayers of your layers draw themselves and their content is composed on top of your layer. That is why you see the text of the text layer.
If you add a text layer like this you can make your code more efficient by not having to do any manual drawing. This requires that the text layer is added to your layer at some earlier point (only once) and that you don't do any custom drawing (it's often slow).
Only if you had read UIColor's class reference...
UIColor *color = [UIColor colorWithRed:200 / 255.0 green:100 / 255.0 blue: 200 / 255.0 alpha: 1.0];
will solve your problem.
I thing perhaps your frame's coordinate is wrong.
CGRect r = CGRectMake( 500, 300, 200, 100 );
[label setFrame:CGRectMake( 400, 300, 400, 100 )];
Note the iPhone screen size is 320*460 or 3
20*568(iPhone5). In your code you set the x coordinate 400 and 500 which is beyond the screen.
Note your coordinate should follow x<=320 or you can't see it in the screen unless you add this in a scrollview
I have a subclass of UIButton where I overwrite drawRect for a custom looking button.
But now the cell doesn't highlight.
How can I fix this?
I have the code ready for another custom drawRect for when the cell is pressed.
- (void)drawRect:(CGRect)rect
{
//// General Declarations
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();
//// Color Declarations
UIColor* red = [UIColor colorWithRed: 1 green: 0 blue: 0 alpha: 1];
CGFloat redRGBA[4];
[red getRed: &redRGBA[0] green: &redRGBA[1] blue: &redRGBA[2] alpha: &redRGBA[3]];
UIColor* darkRed = [UIColor colorWithRed: (redRGBA[0] * 0.8) green: (redRGBA[1] * 0.8) blue: (redRGBA[2] * 0.8) alpha: (redRGBA[3] * 0.8 + 0.2)];
UIColor* lightRed = [UIColor colorWithRed: (redRGBA[0] * 0.8 + 0.2) green: (redRGBA[1] * 0.8 + 0.2) blue: (redRGBA[2] * 0.8 + 0.2) alpha: (redRGBA[3] * 0.8 + 0.2)];
//// Gradient Declarations
NSArray* redGradientColors = [NSArray arrayWithObjects:
(id)darkRed.CGColor,
(id)lightRed.CGColor, nil];
CGFloat redGradientLocations[] = {0, 1};
CGGradientRef redGradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)redGradientColors, redGradientLocations);
//// Shadow Declarations
CGColorRef shadow = [UIColor lightGrayColor].CGColor;
CGSize shadowOffset = CGSizeMake(0, -0);
CGFloat shadowBlurRadius = 1;
CGColorRef shadow2 = [UIColor blackColor].CGColor;
CGSize shadow2Offset = CGSizeMake(0, -0);
CGFloat shadow2BlurRadius = 2;
//// Rounded Rectangle Drawing
UIBezierPath* roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(35, 5, 250, 50) cornerRadius: 6];
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, shadow2Offset, shadow2BlurRadius, shadow2);
CGContextSetFillColorWithColor(context, shadow2);
[roundedRectanglePath fill];
[roundedRectanglePath addClip];
CGContextDrawLinearGradient(context, redGradient, CGPointMake(160, 55), CGPointMake(160, 5), 0);
////// Rounded Rectangle Inner Shadow
CGRect roundedRectangleBorderRect = CGRectInset([roundedRectanglePath bounds], -shadowBlurRadius, -shadowBlurRadius);
roundedRectangleBorderRect = CGRectOffset(roundedRectangleBorderRect, -shadowOffset.width, -shadowOffset.height);
roundedRectangleBorderRect = CGRectInset(CGRectUnion(roundedRectangleBorderRect, [roundedRectanglePath bounds]), -1, -1);
UIBezierPath* roundedRectangleNegativePath = [UIBezierPath bezierPathWithRect: roundedRectangleBorderRect];
[roundedRectangleNegativePath appendPath: roundedRectanglePath];
roundedRectangleNegativePath.usesEvenOddFillRule = YES;
CGContextSaveGState(context);
{
CGFloat xOffset = shadowOffset.width + round(roundedRectangleBorderRect.size.width);
CGFloat yOffset = shadowOffset.height;
CGContextSetShadowWithColor(context,
CGSizeMake(xOffset + copysign(0.1, xOffset), yOffset + copysign(0.1, yOffset)),
shadowBlurRadius,
shadow);
[roundedRectanglePath addClip];
CGAffineTransform transform = CGAffineTransformMakeTranslation(-round(roundedRectangleBorderRect.size.width), 0);
[roundedRectangleNegativePath applyTransform: transform];
[[UIColor grayColor] setFill];
[roundedRectangleNegativePath fill];
}
CGContextRestoreGState(context);
CGContextRestoreGState(context);
[[UIColor blackColor] setStroke];
roundedRectanglePath.lineWidth = 1;
[roundedRectanglePath stroke];
//// Cleanup
CGGradientRelease(redGradient);
CGColorSpaceRelease(colorSpace);
}
subclassing UIButton does not make sense because it's a kind of assembly/cluster class.
I had best experience creating own buttons when subclassing UIControl and add some custom behavior.
Check also this (you should not subclass UIButton).
Then also check how you highlight UIControl subclass.
i think you can deal with the highlight problem with these methods below
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event;
- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)cancelTrackingWithEvent:(UIEvent *)event;
you can change the color or the image in these method
how to change the backgrond color of view controller from other controller in the app ?
To change the background color of a 'view' you need to set the backgroundColor property on it. This implies that you have access to it. If it was all in one controller you would just use
self.view.backgroundColor = [UIColor redColor];
If it was in a navigation or similar based app, then you can access a views parentViewController and change the color on it as follows:
self.parentViewController.view.backgroundColor = [UIColor redColor];
If this is not possible then you can set an iVar on the second view controller when it is created that contains the instance of the viewController that you want to change the background color on.
MyViewController* secondViewController = [[MyViewController alloc] init];
secondViewController.bgColorNeedsChangingViewController = self;
Then in the secondViewController's logic
self.bgColorNeedsChangingViewController.view.backgroundColor = [UIColor redColor];
UIColor *colour = [[UIColor alloc]initWithRed:57.0/255.0 green:156.0/255.0 blue:52.0/255.0 alpha:1.0];
self.view.backgroundColor = colour;
Adapted from Frank Shearar's answer.
UIViewController *yourVC;
UIColor *colour = [[UIColor alloc] initWithRed: 1.0 green: 0.0 blue: 0.0 alpha: 1.0];
[yourVC.view.backgrounColor] = colour;
[colour release];
For changing the background color of a view use this single line of code
self.view.backgroundColor = UIColor (red: 1.0, green: 1.0, blue: 0.5, alpha: 1.0)
The values of red, green, blue and alpha vary btw 0 to 1.
You can also write it as
self.view.backgroundColor = UIColor (red: 123.0/255.0, green: 200.0/255.0, blue: 90.0/255.0, alpha: 1.0)
This is in the entire range of color scheme.