How to change the background of a UIimageview to hex value - iphone

I want to change the background color of my UIimageview. I am aware of how to do it like this
ColorBox.backgroundColor = [UIColor blueColor];
However, my program requires that the backgroundColor be set to a Hex color value. How do i set to a Hex color instead of a UIimage text color?

I have found a link which can answer you.
Please visit http://arstechnica.com/apple/guides/2009/02/iphone-development-accessing-uicolor-components.ars

Assuming you have the individual hex value for red, green and blue. This should work.
int red = [[NSString stringWithFormat:#"%d", redHex] intValue];
int green = [[NSString stringWithFormat:#"%d", greenHex] intValue];
int blue = [[NSString stringWithFormat:#"%d", blueHex] intValue];
[UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1]
Or use this to parse the string:
How can I convert RGB hex string into UIColor in objective-c?

Related

How to change background color of Custom NSView with a custom color [duplicate]

i am trying to compose colors using NSColor and when i am trying to create RGB color with the following values it just displays the white colors instead:
(r,g,b):(50,50,50)
(r,g,b):(100,100,100)
(r,g,b):(150,150,150)
(r,g,b):(200,200,200)
etc...
the code used to create the colors is:
// the code to genearet simple images with background colors
NSColor * myColor = [NSColor colorWithDeviceRed:100.0 green:100.0 blue:100.0 alpha:1.0];
NSImage* image1 = [[NSImage alloc] initWithSize:NSMakeSize(10.0, 100.0)];
NSRect imageBounds1 = NSMakeRect (0, 0, 10, 100);
[image1 lockFocus];
[myColor set];
NSRectFill (imageBounds1);
[image1 unlockFocus];
I couldn't find any resource or sample on the web, which provides some sort of help on my above queries.It's highly appreciated if someone could share his wisdom on how I can achieve this.
Thanks in advance..
If I recall correctly you'll want the range 0-1 as your RGB as well
NSColor components have values in [0..1] so you should normalize the values you have, e.g.:
NSColor * myColor = [NSColor colorWithDeviceRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1.0];
If you try to set values greater then 1 to colour components then they're interpreted as 1, so your code will be actually equivalent to
NSColor * myColor = [NSColor colorWithDeviceRed:1.0 green:1.0 blue:1.0 alpha:1.0];
Which creates white colour.
As stated in the documentation:
Values below 0.0 are interpreted as 0.0, and values above 1.0 are interpreted as 1.0
This means that your values (100,100,100) are going to be converted in (1.0,1.0,1.0) which is white. What you have to do is convert each channel value using the following equation:
100 : 255 = x : 1.0 => x = 100/255
where x is the value that you will use for the method
-(NSColor*)colorWithDeviceRed:CGFloat red green:CGFloat green blue:CGFloat blue alpha:CGFloat alpha];
You should have something like this in your code
[NSColor colorWithDeviceRed:100.0/255.0 green:100.0/255.0 blue:100.0/255.0 alpha:1.0];

Modifying entire NSMutableAttributedString using addAttribute:

I am looking for a way to color the first word in a sentence a different color to that of the rest of the sentence. METHOD_001 first colors the whole string white then re-colors the first 8 characters red. METHOD_002 colors the first 8 characters red, before using the string length to calculate the remaining characters and color them white.
METHOD_001 is definitely the best, but I am curious if there is a simpler way, I was expecting to find a NSMutableAttributedString addAttribute: that did not take a range and just applied the attribute to the whole string, it seems a bit of an oversight that all modifications to a NSMutableAttributedString require you to specify a range, am I missing something?
NB: Code includes hard coded values to aid readability.
// METHOD_001
NSMutableAttributedString *attrString_001 = [[NSMutableAttributedString alloc] initWithString:#"Distance 1720 mm" attributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}];
[attrString_001 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 8)];
[[self nameLabel] setAttributedText:attrString_001];
// METHOD_002
NSString *string = #"Distance 1720 mm";
NSUInteger stringLength = [string length];
NSMutableAttributedString *attrString_002 = [[NSMutableAttributedString alloc] initWithString:string];
[attrString_002 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 8)];
[attrString_002 addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(9, (stringLength-9))];
[[self distanceLabel] setAttributedText:attrString_002];
Actually there is quite an easy way to do that. Even if you set an attributed text to your label, first it is stylized by the regular properties of the label, it is then your attributed string overrides corresponding ones. So if you do [distanceLabel setTextColor:[UIColor whiteColor]] beforehand (in storyboard or code) you can recolor only the needed parts by using attr. strings and achieve your desired effect.

How do i call class method dynamically in IOS?

I'm stuck with a problem here in UIColor.
I'll be getting color names from webservices like
Red, Blue, Magenta ....... and so.
how can i set the backgroundColor of a view using this.
i can only find class methods with these color names ([UIColor redColor], [UIColor blueColor], [UIColor magentaColor]) but i'm not able to write a code which programatically calls these methods cause the color names i get are dynamic.
PLease Help.....
Thank you.
Something like this should work:
NSString *colorFromWeb = #"Red"; // for example
NSString *selectorName = [NSString stringWithFormat:#"%#Color", [colorFromWeb lowercaseString]];
SEL selector = NSSelectorFromString(selectorName);
if ([UIColor respondsToSelector:selector])
UIColor *color = [UIColor performSelector:selector]; // Equivalent to [UIColor redColor];
Here you can Follow Two Approach.
1).Here you can make the call to the color Method by passing the Name of these coming Colors.
As Scott explain in his Answer.
NSString *colorFromWeb = #"Red"; // for example
NSString *selectorName = [NSString stringWithFormat:#"%#Color", [colorFromWeb lowercaseString]];
SEL selector = NSSelectorFromString(selectorName);
if ([UIColor respondsToSelector:selector])
UIColor *color = [UIColor performSelector:selector]; // Equivalent to [UIColor redColor];
2).In Above way you may face some trouble suppose you got some color name form Your WebService which is not exist in UIColor Class then in that case you can not get that desirable color or might be your app could crashed etc.
Here I would Suggest you you should ask the RGB float Values From your Webservice Provider.In this way You can easily pass These RGB and can make Color with these RGB
Here is Some Demo.
[UIColor colorWithRed:redRGB green:greenRGB blue:blueRGB alpha:1.0];
You just need to obtain redRGB,greenRGBand blueRGB from WebService.
In this You can' face any Crash.
I hope It may clears To you.
The Key Value Coding mechanism allows you to interact with class's properties using string representations of the property names.
NSString* colorString = #"redColor";
UIColor* color = [UIColor valueForKey:colorString];

Use CATextLayer with CGContext

I need to draw text into a CGContext and want to use CATextLayer to set the text. Can anyone give me some steps as to how it'll be done. I've written some code for it, but don't know the correctness of it (since I'm new to iPhone Development).
Some basic questions :
1. How to obtain position and size of text for setting the CATextLayer frame
2. The text is somehow coming out inverted which I've fixed using CGAffineTransform, but its a hacky fix and I want to know the actual reason why the text is coming out inverted.
3. I also need to set the text border width and color for which I'm using NSAttributedString, but setting the text size (increasing or decreasing) does not reflect on the screen.
EDIT 1 :
I've updated the code as per your recommendations, but the text is not resizing even after using CTFontRef. Also, on the iPhone the text is getting truncated a little bit from the top. Any idea what's being set incorrectly? When I checked the values I'm getting from getTypographicBounds, they're all 0 (origin.x, origin.y, width and height).
The getTypographicBounds method :
width = CTLineGetTypographicBounds(m_line, &ascent, &descent, &leading);
// Return text bounds
return CGRectMake(0, 0, width, ascent + descent);
The modified code :
CATextLayer* text = [[CATextLayer alloc] init];
CGColorSpaceRef rgbColor = CGColorSpaceCreateDeviceRGB();
CGColorRef rgb = CGColorCreate(rgbColor, m_fill_color);
text.foregroundColor = rgb;
text.frame = CGRectMake([self getTypographicBounds].origin.x, [self getTypographicBounds].origin.y, [self getTypographicBounds].size.width + 2*m_padding, [self getTypographicBounds].size.height + 2*m_padding);
text.wrapped = YES;
NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];
CTFontRef aCFFont = CTFontCreateWithName ((CFStringRef)m_font_name, 30.0, NULL);
// Set a negative width so we get both stroke and fill to show
[stringAttributes setObject: (NSObject*)aCFFont forKey: (id)kCTFontNameAttribute];
[stringAttributes setObject: [NSNumber numberWithFloat: -3 ] forKey: (id)kCTStrokeWidthAttributeName];
[stringAttributes setObject: [UIColor whiteColor] forKey: (id)kCTStrokeColorAttributeName];
NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:m_text
attributes:stringAttributes];
text.string = (NSString*)stringToDraw;
[text drawInContext:ctx];
EDIT 2 : The wiki example uses CTLine, I'm using CATextLayer. Reason :: CATextLayer lets me modify text during runtime to show Chinese, Japanese, Hindi, Russian and all languages with different scripts. Also, CATextLayer seems to render with more clarity than CoreText.
The issue I'm facing right now is that the text being displayed by [text drawInContext:ctx] line is truncating from the top. I checked the frame and text font size. Font size is 16 px and frame height is 17.768, so I don't know why it's truncating.
// Ensure CTLine is up-to-date
if (m_is_dirty)
[self recomputeLine];
// Get text metrics
CGFloat width;
CGFloat ascent;
CGFloat descent;
CGFloat leading;
width = CTLineGetTypographicBounds(m_line, &ascent, &descent, &leading);
// Position text so that top of text aligns with top of layer
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity );
// Setup text drawing style
CGContextSetRGBFillColor (ctx, m_fill_color [0], m_fill_color [1], m_fill_color [2], 1.0);
CGContextSetRGBStrokeColor (ctx, m_stroke_color[0], m_stroke_color[1], m_stroke_color[2], 1.0);
CGContextSetFont (ctx, m_font );
CGContextSetFontSize (ctx, m_font_size );
CGContextSetLineWidth (ctx, m_stroke_width);
CATextLayer* text = [[CATextLayer alloc] init];
CGColorSpaceRef rgbColor = CGColorSpaceCreateDeviceRGB();
CGColorRef rgb = CGColorCreate(rgbColor, m_fill_color);
text.foregroundColor = rgb;
text.fontSize = m_font_size;
text.font = m_font;
text.frame = CGRectMake([self getTypographicBounds].origin.x, [self getTypographicBounds].origin.y, [self getTypographicBounds].size.width, [self getTypographicBounds].size.height);
text.wrapped = YES;
NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];
// Set a negative width so we get both stroke and fill to show
[stringAttributes setObject: [UIFont fontWithName:m_font_name size:m_font_size] forKey: (id)kCTFontNameAttribute];
[stringAttributes setObject: [NSNumber numberWithFloat: -3 ] forKey: (id)kCTStrokeWidthAttributeName];
[stringAttributes setObject: [UIColor whiteColor] forKey: (id)kCTStrokeColorAttributeName];
NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:m_text
attributes:stringAttributes];
text.string = (NSString*)stringToDraw;
[text drawInContext:ctx];
Thanks in advance
Nick
It is because of the flipped coordinate space used for CGContexts. For a full explanation (with diagrams) see here.
EDIT:
To control the position translate your context before drawing the text:
CGContextTranslateCTM(context, x, y);
EDIT 2:
Looks like you need to use a CTFontRef, not a UIFont. For an example, see here (see post by Gordon Apple Wed Jun 23 10:40:23 2010).
EDIT 3:
Unless you specifically need to use NSAttributedString, I would recommend using the much simpler NSString drawInRect:withFont:lineBreakMode:alignment: method. It creates a CATextLayer for you, but is much simpler to use:
UIFont *font = [UIFont fontWithName:m_font_name size:30.f];
[m_text drawInRect:text.frame withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
EDIT 4:
Try setting your dictionary like this:
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)fontName, pointSize,NULL);
CGColorRef color = textColor.CGColor;
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
(__bridge id)ctFont, (id)kCTFontAttributeName,
color, (id)kCTForegroundColorAttributeName,nil];

NSString sizeWithFont: returning inconsistent results? known bug?

I'm trying to create a simple custom UIView wich contain a string drawn with a single font, but where the first character is slightly larger.
I thought this would be easily implemented with two UILabel:s placed next to eachother.
I use NSString sizeWithFont to measure my string to be able to lay it out correctly.
But I noticed that the font baseline in the returned rectangle varies with +/- 1 pixel depending on the font size I set.
Here is my code:
NSString* ctxt = [text substringToIndex:1];
NSString* ttxt = [text substringFromIndex:1];
CGSize sz = [ctxt sizeWithFont: cfont ];
clbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, sz.width, sz.height)];
clbl.text = ctxt;
clbl.font = cfont;
clbl.backgroundColor = [UIColor clearColor];
[contentView addSubview:clbl];
CGSize sz2 = [ttxt sizeWithFont: tfont];
tlbl = [[UILabel alloc] initWithFrame:CGRectMake(sz.width, (sz.height - sz2.height), sz2.width, sz2.height)];
tlbl.text = ttxt;
tlbl.font = tfont;
tlbl.backgroundColor = [UIColor clearColor];
[contentView addSubview:tlbl];
If I use 12.0 and 14.0 as sizes, it works fine.
But if I instead use 13.0 and 15.0, then the first character is 1 pixel too high.
Is this a known problem?
Any suggestions how to work around it?
Creating a UIWebView with a CSS and HTML page seems way overkill for this. and more work to handle dynamic strings. Is that what I'm expected to do?
Found the answer...
Ofcourse, I also have to check the descender value on the font, and compensate for that in the layout.
New rect for the second label is:
CGRectMake(sz.width, (sz.height - sz2.height) + floor(cfont.descender - tfont.descender), sz2.width, sz2.height)
floor() is to make sure it snaps to pixel position, or the font will look blurry