How to draw UILabel Into Context - ios

I'm trying to draw a UIlabel into a new Context, at a specific location. I know you can draw just the NSString into a context easily, but I want to retain the text size, color, and word wrap style of the UILabel. Thanks for your help!
UIGraphicsBeginImageContext(targetSize);
// here is where I want to draw UILabel to context
UIGraphicsEndImageContext();

You could draw any view using -renderInContext:, but if all you need is just retain the text size, color and word wrap style, you could simply use -drawInRect:withFont:lineBreakMode:alignment: to customize all options.
[label.textColor set];
[label.text drawInRect:label.bounds
withFont:label.font
lineBreakMode:label.lineBreakMode
alignment:label.textAlignment];
There is also a -drawTextInRect: method in UILabel, but Apple says "You should not call this method directly."

Related

Drawing an object of NSString in a Rectangle.

I'm trying to put a string in a rectangular form via drawInRect:withAttributes: method. The official documentation writes: "Draws the receiver with the font and other display characteristics of the given attributes, within the specified rectangle in the currently focused UIView."
This action should be done on a button event. But it doesn't work at all. Nothing is shown.
The code that I use:
- (IBAction)buttonPressed:(id)sender
{
// some area on the top (a part of UIView)
CGRect rect = CGRectMake(50, 50, 100, 100);
// my text
NSString *str = #"Eh, what's wrong with this code?";
// crappy attributes
NSDictionary *attributes = #{NSFontAttributeName: [UIFont boldSystemFontOfSize:8]};
// and finally passing a message
[str drawInRect:rect withAttributes:attributes];
}
Is there a particular kind of areas that might be used for drawing strings in rects? Or is it possible to draw a string in a rect where I'd like it to be? Please, help me understand it better!
But it doesn't work at all. Nothing is shown.
That's because no drawing context is set up when you run that code. You're looking at drawing as something that you can do whenever you feel like it, but in fact drawing is something that you should only do when the system asks you to. At other times, you should instead remember what you want to draw, and then draw it when the time comes.
When is "the time" to draw? It's when your view's -drawRect: method is called. Since your method is an action, it looks like you're probably trying to do the drawing in a view controller. What you want to do instead is to subclass UIView and override -drawRect: to draw what you want.
It doesn't work that way, you first need to make a CGContextRef where you will draw the text.
Your code is fine, just place everything within drawRect.

How to manipulate individual character of UITextView in ios?

I want to manipulate individual character of UITextView like rotating one to the left(90 degrees) and one to the right(90 degrees), and so on.
Anyone has an idea on achieving this?
The easiest thing to modify individual characters in an UITextView is to use NSMutableAttributedString by extending it like this:
#implementation NSMutableAttributedString (Rotation)
- (void)setRotatedFontWithName:(NSString*)fontName
size:(CGFloat)size
range:(NSRange)range
{
CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI_2);
CTFontRef aFont = CTFontCreateWithName((CFStringRef)fontName, size, &transform);
if (!aFont)
return;
[self removeAttribute:(NSString*)kCTFontAttributeName range:range];
[self addAttribute:(NSString*)kCTFontAttributeName value:(id)aFont range:range];
CFRelease(aFont);
}
And then using the attributedText property of a UITextField to set the rotated font.
What you could also try is creating a custom class that overrides UITextField's default drawRect: and draw the normal and rotated text using Core Text methods (see the example in here, section about rendering text on a curved shape)

Stretch width of UILabel according to width of containing text with background image

I have the following problem - I need to create two UI labels along side one another as in the screen shot below -
The UI label containing the special offers text is dynamic and needs to adjust to the width of the containing text and also if possible display the slanted orange background with the relevant padding -
I'm predominantly a Front-end dev - so with CSS i'd use a long background image that aligns to the right of the label and pad accordingly - but I have no idea how to approach this in objective C - can anyone offer any advice?
This is not a drop-in solution, but perhaps helps you find it (assuming you don't use Auto Layout):
You need a UIImageView for the background and a UILabel for the text
Use a tileable/strechable image (probably with cap insets) for the background (see [UIImage resizableImageWithCapInsets:resizingMode:])
Set the text on your label
Call [label sizeToFit] to resize the label to exactly fit the contained text
Resize the image view depending on the label's size (e.g. imageView.frame = CGRectInset(label.frame, -10, -10), which would make your image view 10pt larger than the label on all sides).
With Auto Layout you'd just define the appropriate constraints between the label and the image view and rely on the label's "intrinsic content size" - should be quite easy.
You could always shrink the text when it gets to long for the label, go into your view controller, click on the label that you would like to shrink when the text gets too long, then, go down to Autoshrink under Label in the attributes inspector. Change it from fixed font size to minimum font size, then I recommend putting 6 to 8 as the lowest font size. This is going to be the LOWEST font size though, so if XCode can make the label fit while making the font size 9, yet the lowest is 7, it will do it.
Or, you could get the length of the string with
int *stringLength = [myString length]
which counts spaces too, then, change the orange square with
orangeBoxImageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight);
so you could do something like this with your code:
if(stringLength == 15{
orangeBoxImageView.frame = CGRectMake(0, 0, 15, 5);
}
I hope this could help you
CGFloat rect = [YOURSTRING
boundingRectWithSize: (CGSize){ labelWidth, CGFLOAT_MAX }
options: NSStringDrawingUsesLineFragmentOrigin
attributes: #{ NSFontAttributeName : labelFont };
context: nil];
This assumes numberOfLines = 0.
What you want to use is UILabel -sizeToFit inherited from UIView. You should be able to figure out the rest from there.
Find the size of the containing text with
[text sizeWithFont:font constrainedToSize:CGSizeMake(width, height) lineBreakMode:NSLineBreakModexx]
Once you have that, you can manipulate the size of the label accordingly.
Hope this helps
For the background I'd create a subclass of UILabel that overrides drawInRect:, such as this example that simply draws a rectangle with the size of the label
-(void) drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, [UIColor redColor].CGColor);
CGContextFillRect(context, rect);
}
Rather than drawing a rectangle, you should create a path with the shape that you need and fill that. See here for more info:
http://weblog.invasivecode.com/core-graphics
I don't know how you've created your label, but if it's done properly with autolayout it'll have the correct width automagically. See here:
http://www.raywenderlich.com/20881/
Tim

Draw text and add to a UIImage iOS 5/6

I have a textbox, where i want the written text to be added to a UIImage.
How can i draw NSString to a UIImage?
I´ve searched, and found lots of examples, but non of them works. Xcode just gives me lots of errors.
Simply put, i want to draw a NSString to a UIimage. The UIImage should be the same size as a predefined UIImageView, and be placed in center.
Any ideas?
i think solution is here..i have used this method in one of my application
here lbltext is the object of my label. this method creates new image with given text & return the object of new image with text.
-(UIImage *) drawText:(NSString*) text inImage:(UIImage*)image atPoint:(CGPoint)point
{
UIFont *font = lblText.font;
UIGraphicsBeginImageContext(iv.frame.size);
[image drawInRect:CGRectMake(0,0,iv.frame.size.width,iv.frame.size.height)];
CGRect rect = CGRectMake(point.x,point.y,lblText.frame.size.width, lblText.frame.size.height);
[lblText.textColor set];
[text drawInRect:CGRectIntegral(rect) withFont:font];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
in your below comment you have passed iv.center as a point.. try manualy like this
CGPoint point;
point.x=30; // dynamicaly just for example lblText.frame.origin.x;
point.y=40; //lblText.frame.origin.y;
you have to call above method like this...
UIImage *img = [self drawText:#"Test String" inImage:originalImage atPoint:point];
here,img is another instace of UIImage for storing new image with text...after calling this method use img imager for your further use..
for example...
[newimageviewObj setImage:img];
i hope this will help you
UIImage is not a subview of UIView, so you cant add a subview to it. Also NSString is not a subview of UIView. If you want to show things on the screen, they should inherit from UIView.
So try this:
Create a UIImageView - set its image property to be your UIImage instance.
Create a UILabel - set its text property to your NSString.
Add the UILabel as a subview of your UIImageView.
and finally add your UIImageView to your current view controllers view.
Emm, here is some thoughts.
I think that one simple way is like this :
Put aUIImageView on aView;
Add aUITextView on aView;
Get ScreenShot from aView;
This may works fine.
Also, this may come with a problem that screenshot may be not clear.
Then, After step1 and step2, we may get new image by UIGraphics.
(With here, we already know position where text should be on image and this should be ok.)
PS: Some image may not have some attribution like CGImage and CGImage is needed for this. So, transform it.

Is there a way to have stroke for UIFont

I'm using MKMap with overlay. The overlay display text. I need the text to have "stroke" effect. any clue?
[t drawAtPoint:CGPointMake(0,30) withFont:[UIFont fontWithName:#"Helvetica-Bold" /*"Arial"*/ size:(3 * MKRoadWidthAtZoomScale(zoomScale))]
];
If you're drawing in drawRect:, you can set the text drawing mode using:
CGContextSetTextDrawingMode(UIGraphicsGetCurrentContext(), kCGTextStroke);
If you wanted to fill and stroke, then you can use kCGTextFillStroke.
You can create an CFAttributedString from your string, set appropriate kCTStrokeWidthAttributeName and kCTStrokeColorAttributeName attribute values and draw it with CoreText framework.

Resources