Why is this text changing characters in Yosemite? - objective-c

I'm trying to update an app for Yosemite, and one weird problem I'm getting is that the text labels on a custom control are changing characters - not distorting, but changing from "ON" to "KJ" and "OFF" to "KBB". The documents are all encoded as UTF-8 files. If anyone has any ideas, I'd love to hear them.
The code in question:
AKDrawStringAlignedInFrame(#"OFF", [NSFont boldSystemFontOfSize:0], NSCenterTextAlignment, NSIntegralRect(textRects[0]));
which calls:
void AKDrawStringAlignedInFrame(NSString *text, NSFont *font, NSTextAlignment alignment, NSRect frame) {
NSCParameterAssert(font != nil);
NSBezierPath *textPath = [NSBezierPath bezierPathWithString:text inFont:font];
NSRect textPathBounds = NSMakeRect(NSMinX([textPath bounds]), [font descender], NSWidth([textPath bounds]), [font ascender] - [font descender]);
NSAffineTransform *scale = [NSAffineTransform transform];
CGFloat xScale = NSWidth(frame)/NSWidth(textPathBounds);
CGFloat yScale = NSHeight(frame)/NSHeight(textPathBounds);
[scale scaleBy:MIN(xScale, yScale)];
[textPath transformUsingAffineTransform:scale];
textPathBounds.origin = [scale transformPoint:textPathBounds.origin];
textPathBounds.size = [scale transformSize:textPathBounds.size];
NSAffineTransform *originCorrection = [NSAffineTransform transform];
NSPoint centeredOrigin = NSRectFromCGRect(AFRectCenteredSize(NSRectToCGRect(frame), NSSizeToCGSize(textPathBounds.size))).origin;
[originCorrection translateXBy:(centeredOrigin.x - NSMinX(textPathBounds)) yBy:(centeredOrigin.y - NSMinY(textPathBounds))];
[textPath transformUsingAffineTransform:originCorrection];
if (alignment != NSJustifiedTextAlignment && alignment != NSCenterTextAlignment) {
NSAffineTransform *alignmentTransform = [NSAffineTransform transform];
CGFloat deltaX = 0;
if (alignment == NSLeftTextAlignment) deltaX = -(NSMinX([textPath bounds]) - NSMinX(frame));
else if (alignment == NSRightTextAlignment) deltaX = (NSMaxX(frame) - NSMaxX([textPath bounds]));
[alignmentTransform translateXBy:deltaX yBy:0];
[textPath transformUsingAffineTransform:alignmentTransform];
}
[textPath fill];
}
and +[NSBezierPath bezierPathWithString:inFont:] is just
+ (NSBezierPath *)bezierPathWithString:(NSString *)text inFont:(NSFont *)font {
NSBezierPath *textPath = [self bezierPath];
[textPath appendBezierPathWithString:text inFont:font];
return textPath;
}
Lastly, -[appendBezierPathWithString:text] is:
- (void)appendBezierPathWithString:(NSString *)text inFont:(NSFont *)font {
if ([self isEmpty]) [self moveToPoint:NSZeroPoint];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text];
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)attributedString);
CFArrayRef glyphRuns = CTLineGetGlyphRuns(line);
CFIndex count = CFArrayGetCount(glyphRuns);
for (CFIndex index = 0; index < count; index++) {
CTRunRef currentRun = (CTRunRef)CFArrayGetValueAtIndex(glyphRuns, index);
CFIndex glyphCount = CTRunGetGlyphCount(currentRun);
CGGlyph glyphs[glyphCount];
CTRunGetGlyphs(currentRun, CTRunGetStringRange(currentRun), glyphs);
NSGlyph bezierPathGlyphs[glyphCount];
for (CFIndex glyphIndex = 0; glyphIndex < glyphCount; glyphIndex++)
bezierPathGlyphs[glyphIndex] = glyphs[glyphIndex];
[self appendBezierPathWithGlyphs:bezierPathGlyphs count:glyphCount inFont:font];
}
CFRelease(line);
}

Glyph indices are specific to a font. The appendBezierPathWithString:inFont: method gets the glyph indices from Core Text (CTLine and CTRun) but it's not providing the font. Presumably, Core Text is using a default font. Later, it's using those glyph indices but it's passing the desired font, not the font that Core Text used. So, the glyph indices don't mean the same thing.
I think the solution is to construct the attributed string in that method with a font attribute:
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text attributes:#{ NSFontAttributeName: font }];
(Normally, you have to be careful about using attributes that Core Text will understand, but I believe that NSFontAttributeName maps to kCTFontAttributeName and NSFont is toll-free bridged to CTFont.)

Related

Autosize Text in Label for PaintCode CGContext

I'm using the following to draw text inside a Bezier Path. How can i adjust this to allow the text to autosize.
EDIT
I was able to update to iOS7 methods but still nothing. I can autosize text within a UILabel fine, but because this is CGContext it is harder
NSString* textContent = #"LOCATION";
NSMutableParagraphStyle* locationStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;
locationStyle.alignment = NSTextAlignmentCenter;
NSDictionary* locationFontAttributes = #{NSFontAttributeName: [UIFont fontWithName:myFont size: 19], NSForegroundColorAttributeName: locationColor, NSParagraphStyleAttributeName: locationStyle};
CGFloat locationTextHeight = [textContent boundingRectWithSize: CGSizeMake(locationRect.size.width, INFINITY) options: NSStringDrawingUsesLineFragmentOrigin attributes: locationFontAttributes context: nil].size.height;
CGContextSaveGState(context);
CGContextClipToRect(context, locationRect);
[textContent drawInRect: CGRectMake(CGRectGetMinX(locationRect), CGRectGetMinY(locationRect) + (CGRectGetHeight(locationRect) - locationTextHeight) / 2, CGRectGetWidth(locationRect), locationTextHeight) withAttributes: locationFontAttributes];
CGContextRestoreGState(context);
Try using this method of NSAttributedString:
- (CGRect)boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
context:(NSStringDrawingContext *)context;
Where the context will provide you actualScaleFactor.
The usage is something like this:
NSAttributedString *string = ...;
NSStringDrawingContext *context = [NSStringDrawingContext new];
context.minimumScaleFactor = 0.5; // Set your minimum value.
CGRect bounds = [string boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
context:context];
CGFloat scale = context. actualScaleFactor;
// Use this scale to multiply font sizes in the string, so it will fit.

Replacement for deprecated sizeWithFont: in iOS 7?

In iOS 7, sizeWithFont: is now deprecated. How do I now pass in the UIFont object into the replacement method sizeWithAttributes:?
Use sizeWithAttributes: instead, which now takes an NSDictionary. Pass in the pair with key UITextAttributeFont and your font object like this:
CGRect rawRect = {};
rawRect.size = [string sizeWithAttributes: #{
NSFontAttributeName: [UIFont systemFontOfSize:17.0f],
}];
// Values are fractional -- you should take the ceil to get equivalent values
CGSize adjustedSize = CGRectIntegral(rawRect).size;
I believe the function was deprecated because that series of NSString+UIKit functions (sizewithFont:..., etc) were based on the UIStringDrawing library, which wasn't thread safe. If you tried to run them not on the main thread (like any other UIKit functionality), you'll get unpredictable behaviors. In particular, if you ran the function on multiple threads simultaneously, it'll probably crash your app. This is why in iOS 6, they introduced a the boundingRectWithSize:... method for NSAttributedString. This was built on top of the NSStringDrawing libraries and is thread safe.
If you look at the new NSString boundingRectWithSize:... function, it asks for an attributes array in the same manner as a NSAttributeString. If I had to guess, this new NSString function in iOS 7 is merely a wrapper for the NSAttributeString function from iOS 6.
On that note, if you were only supporting iOS 6 and iOS 7, then I would definitely change all of your NSString sizeWithFont:... to the NSAttributeString boundingRectWithSize. It'll save you a lot of headache if you happen to have a weird multi-threading corner case! Here's how I converted NSString sizeWithFont:constrainedToSize::
What used to be:
NSString *text = ...;
CGFloat width = ...;
UIFont *font = ...;
CGSize size = [text sizeWithFont:font
constrainedToSize:(CGSize){width, CGFLOAT_MAX}];
Can be replaced with:
NSString *text = ...;
CGFloat width = ...;
UIFont *font = ...;
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:text
attributes:#{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
Please note the documentation mentions:
In iOS 7 and later, this method returns fractional sizes (in the size
component of the returned CGRect); to use a returned size to size
views, you must use raise its value to the nearest higher integer
using the ceil function.
So to pull out the calculated height or width to be used for sizing views, I would use:
CGFloat height = ceilf(size.height);
CGFloat width = ceilf(size.width);
As you can see sizeWithFont at Apple Developer site it is deprecated so we need to use sizeWithAttributes.
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
NSString *text = #"Hello iOS 7.0";
if (SYSTEM_VERSION_LESS_THAN(#"7.0")) {
// code here for iOS 5.0,6.0 and so on
CGSize fontSize = [text sizeWithFont:[UIFont fontWithName:#"Helvetica"
size:12]];
} else {
// code here for iOS 7.0
CGSize fontSize = [text sizeWithAttributes:
#{NSFontAttributeName:
[UIFont fontWithName:#"Helvetica" size:12]}];
}
I created a category to handle this problem, here it is :
#import "NSString+StringSizeWithFont.h"
#implementation NSString (StringSizeWithFont)
- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
if ([self respondsToSelector:#selector(sizeWithAttributes:)])
{
NSDictionary* attribs = #{NSFontAttributeName:fontToUse};
return ([self sizeWithAttributes:attribs]);
}
return ([self sizeWithFont:fontToUse]);
}
This way you only have to find/replace sizeWithFont: with sizeWithMyFont: and you're good to go.
In iOS7 I needed the logic to return the correct height for the tableview:heightForRowAtIndexPath method, but the sizeWithAttributes always returns the same height regardless of the string length because it doesn't know that it is going to be put in a fixed width table cell. I found this works great for me and calculates the correct height taking in consideration the width for the table cell! This is based on Mr. T's answer above.
NSString *text = #"The text that I want to wrap in a table cell."
CGFloat width = tableView.frame.size.width - 15 - 30 - 15; //tableView width - left border width - accessory indicator - right border width
UIFont *font = [UIFont systemFontOfSize:17];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:#{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
size.height = ceilf(size.height);
size.width = ceilf(size.width);
return size.height + 15; //Add a little more padding for big thumbs and the detailText label
Multi-line labels using dynamic height may require additional information to set the size properly. You can use sizeWithAttributes with UIFont and NSParagraphStyle to specify both the font and the line-break mode.
You would define the Paragraph Style and use an NSDictionary like this:
// set paragraph style
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];
// make dictionary of attributes with paragraph style
NSDictionary *sizeAttributes = #{NSFontAttributeName:myLabel.font, NSParagraphStyleAttributeName: style};
// get the CGSize
CGSize adjustedSize = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
// alternatively you can also get a CGRect to determine height
CGRect rect = [myLabel.text boundingRectWithSize:adjustedSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:sizeAttributes
context:nil];
You can use the CGSize 'adjustedSize' or CGRect as rect.size.height property if you're looking for the height.
More info on NSParagraphStyle here: https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSParagraphStyle_Class/Reference/Reference.html
// max size constraint
CGSize maximumLabelSize = CGSizeMake(184, FLT_MAX)
// font
UIFont *font = [UIFont fontWithName:TRADE_GOTHIC_REGULAR size:20.0f];
// set paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
// dictionary of attributes
NSDictionary *attributes = #{NSFontAttributeName:font,
NSParagraphStyleAttributeName: paragraphStyle.copy};
CGRect textRect = [string boundingRectWithSize: maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGSize expectedLabelSize = CGSizeMake(ceil(textRect.size.width), ceil(textRect.size.height));
Create a function that takes a UILabel instance. and returns CGSize
CGSize constraint = CGSizeMake(label.frame.size.width , 2000.0);
// Adjust according to requirement
CGSize size;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){
NSRange range = NSMakeRange(0, [label.attributedText length]);
NSDictionary *attributes = [label.attributedText attributesAtIndex:0 effectiveRange:&range];
CGSize boundingBox = [label.text boundingRectWithSize:constraint options: NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
}
else{
size = [label.text sizeWithFont:label.font constrainedToSize:constraint lineBreakMode:label.lineBreakMode];
}
return size;
Alternate solution-
CGSize expectedLabelSize;
if ([subTitle respondsToSelector:#selector(sizeWithAttributes:)])
{
expectedLabelSize = [subTitle sizeWithAttributes:#{NSFontAttributeName:subTitleLabel.font}];
}else{
expectedLabelSize = [subTitle sizeWithFont:subTitleLabel.font constrainedToSize:subTitleLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping];
}
Building on #bitsand, this is a new method I just added to my NSString+Extras category:
- (CGRect) boundingRectWithFont:(UIFont *) font constrainedToSize:(CGSize) constraintSize lineBreakMode:(NSLineBreakMode) lineBreakMode;
{
// set paragraph style
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:lineBreakMode];
// make dictionary of attributes with paragraph style
NSDictionary *sizeAttributes = #{NSFontAttributeName:font, NSParagraphStyleAttributeName: style};
CGRect frame = [self boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:sizeAttributes context:nil];
/*
// OLD
CGSize stringSize = [self sizeWithFont:font
constrainedToSize:constraintSize
lineBreakMode:lineBreakMode];
// OLD
*/
return frame;
}
I just use the size of the resulting frame.
You can still use sizeWithFont. but, in iOS >= 7.0 method cause crashing if the string contains leading and trailing spaces or end lines \n.
Trimming text before using it
label.text = [label.text stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
That's also may apply to sizeWithAttributes and [label sizeToFit].
also, whenever you have nsstringdrawingtextstorage message sent to deallocated instance in iOS 7.0 device it deals with this.
Better use automatic dimensions (Swift):
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
NB:
1. UITableViewCell prototype should be properly designed (for the instance don't forget set UILabel.numberOfLines = 0 etc)
2. Remove HeightForRowAtIndexPath method
VIDEO:
https://youtu.be/Sz3XfCsSb6k
boundingRectWithSize:options:attributes:context:
Accepted answer in Xamarin would be (use sizeWithAttributes and UITextAttributeFont):
UIStringAttributes attributes = new UIStringAttributes
{
Font = UIFont.SystemFontOfSize(17)
};
var size = text.GetSizeUsingAttributes(attributes);
As the #Ayush answer:
As you can see sizeWithFont at Apple Developer site it is deprecated so we need to use sizeWithAttributes.
Well, supposing that in 2019+ you are probably using Swift and String instead of Objective-c and NSString, here's the correct way do get the size of a String with predefined font:
let stringSize = NSString(string: label.text!).size(withAttributes: [.font : UIFont(name: "OpenSans-Regular", size: 15)!])
- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
if ([self respondsToSelector:#selector(sizeWithAttributes:)])
{
NSDictionary* attribs = #{NSFontAttributeName:fontToUse};
return ([self sizeWithAttributes:attribs]);
}
return ([self sizeWithFont:fontToUse]);
}
Here is the monotouch equivalent if anyone needs it:
/// <summary>
/// Measures the height of the string for the given width.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="font">The font.</param>
/// <param name="width">The width.</param>
/// <param name="padding">The padding.</param>
/// <returns></returns>
public static float MeasureStringHeightForWidth(this string text, UIFont font, float width, float padding = 20)
{
NSAttributedString attributedString = new NSAttributedString(text, new UIStringAttributes() { Font = font });
RectangleF rect = attributedString.GetBoundingRect(new SizeF(width, float.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin, null);
return rect.Height + padding;
}
which can be used like this:
public override float GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
{
//Elements is a string array
return Elements[indexPath.Row].MeasureStringHeightForWidth(UIFont.SystemFontOfSize(UIFont.LabelFontSize), tableView.Frame.Size.Width - 15 - 30 - 15);
}
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
float heightUse = expectedLabelSize.height;
Try this syntax:
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:text
attributes:#{NSFontAttributeName: font}];
None of this worked for me in ios 7. Here is what I ended up doing. I put this in my custom cell class and call the method in my heightForCellAtIndexPath method.
My cell looks similar to the description cell when viewing an app in the app store.
First in the storyboard, set your label to 'attributedText', set the number of lines to 0 (which will resize the label automatically (ios 6+ only)) and set it to word wrap.
Then i just add up all the heights of the content of the cell in my custom Cell Class. In my case I have a Label at the top that always says "Description" (_descriptionHeadingLabel), a smaller label that is variable in size that contains the actual description (_descriptionLabel) a constraint from the top of the cell to the heading (_descriptionHeadingLabelTopConstraint). I also added 3 to space out the bottom a little bit (about the same amount apple places on the subtitle type cell.)
- (CGFloat)calculateHeight
{
CGFloat width = _descriptionLabel.frame.size.width;
NSAttributedString *attributedText = _descriptionLabel.attributedText;
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options: NSStringDrawingUsesLineFragmentOrigin context:nil];
return rect.size.height + _descriptionHeadingLabel.frame.size.height + _descriptionHeadingLabelTopConstraint.constant + 3;
}
And in my Table View delegate:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (indexPath.row == 0) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"descriptionCell"];
DescriptionCell *descriptionCell = (DescriptionCell *)cell;
NSString *text = [_event objectForKey:#"description"];
descriptionCell.descriptionLabel.text = text;
return [descriptionCell calculateHeight];
}
return 44.0f;
}
You can change the if statement to be a little 'smarter' and actually get the cell identifier from some sort of data source. In my case the cells are going to be hard coded since there will be fixed amount of them in a specific order.

drawWithFrame NSOutlineView Flickr

I have a custom cell class for NSOutlineView
In the cell class I have implemented the drawWithFrame.
The rect provided(cellFrame) I divide into 3 parts
(a) Image
(b) Text
(c) Darwing (ellipse/circle / rectangle)
The image is drawn using [image compositeToPoint:imageFrame.origin operation:NSCompositeSourceOver];
The ellipse is drawn using [[NSBezierPath bezierPathWithRoundedRect:ellipseRect xRadius:10 yRadius:10] fill];
The text rect is given to the super class to draw the text
[super drawInteriorWithFrame:newFrame inView:controlView];
Now my problem is that when any cell of the outline view expands, all the drawing (ellipse etc) flickr and appear to be redrawn, even if the cell was not expanded.
Can anyone help me to resolve this..
Here is the code
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
{
//cellFrame.size.height -=16;
Option *ol = [self representedObject];
uint64_t sz;
int fontSize=10;
NSString *sizeText;
MyFile *tmpf;
//NSImage *image = [ol getImage];
if (image != nil)
{
// the cell has an image: draw the normal item cell
NSSize imageSize;
NSRect imageFrame;
imageSize = [image size];
NSDivideRect(cellFrame, &imageFrame, &cellFrame, 3 + imageSize.width, NSMinXEdge);
imageFrame.origin.x += kImageOriginXOffset;
imageFrame.origin.y -= kImageOriginYOffset;
imageFrame.size = NSMakeSize(12,12);
if ([controlView isFlipped])
imageFrame.origin.y += ceil((cellFrame.size.height + imageFrame.size.height) / 2);
else
imageFrame.origin.y += ceil((cellFrame.size.height - imageFrame.size.height) / 2);
[image compositeToPoint:imageFrame.origin operation:NSCompositeSourceOver];
imageFrame.origin.y+=18;
imageFrame.size.width = cellFrame.size.width - 18;
imageFrame.origin.x+=18;
sz = [ol getsize];
/////////////////////////////////
NSRect newFrame = cellFrame;
newFrame.origin.x += kTextOriginXOffset;
newFrame.origin.y += kTextOriginYOffset;
newFrame.size.height -= kTextHeightAdjust;
newFrame.size.width -= 65;
if(sz)
{
//newFrame.origin.x += 65;
NSRect tmpframe = newFrame;
NSRect ellipseRect = NSMakeRect(tmpframe.origin.x+tmpframe.size.width+1,
tmpframe.origin.y+ kTextOriginYOffset,
60,16);
//////// ****ALLOC ********
tmpf = [[MyFile alloc] init];
[tmpf setfsize:sz];
sizeText = [tmpf getFormattedfize];
// [NSShadow setShadowWithOffset:NSMakeSize(0, -8 * 1) blurRadius:12 * 1
// color:[NSColor colorWithCalibratedWhite:0 alpha:0.75]];
[[NSColor colorWithCalibratedWhite:0.9 alpha:1.0] set];
[[NSBezierPath bezierPathWithRoundedRect:ellipseRect xRadius:10 yRadius:10] fill];
// [NSShadow clearShadow];
TextAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSColor textColor],
NSForegroundColorAttributeName,
[NSFont systemFontOfSize:10],
NSFontAttributeName, nil];
[sizeText drawAtPoint:NSMakePoint(ellipseRect.origin.x+3, ellipseRect.origin.y+2)
withAttributes:TextAttributes];
//////// ****RELEASE *******
[tmpf release];
}
[super drawInteriorWithFrame:newFrame inView:controlView];
}
}

How do you stroke the _outside_ of an NSAttributedString?

I've been using NSStrokeWidthAttributeName on NSAttributedString objects to put an outline around text as it's drawn. The problem is that the stroke is inside the fill area of the text. When the text is small (e.g. 1 pixel thick), the stroking makes the text hard to read. What I really want is a stroke on the outside. Is there any way to do that?
I've tried an NSShadow with no offset and a blur, but it's too blurry and hard to see. If there was a way to increase the size of the shadow without any blur, that would work too.
While there may be other ways, one way to accomplish this is to first draw the string with only a stroke, then draw the string with only a fill, directly overtop of what was previously drawn. (Adobe InDesign actually has this built-in, where it will appear to only apply the stroke to the outside of letter, which helps with readability).
This is just an example view that shows how to accomplish this (inspired by http://developer.apple.com/library/mac/#qa/qa2008/qa1531.html):
First set up the attributes:
#implementation MDInDesignTextView
static NSMutableDictionary *regularAttributes = nil;
static NSMutableDictionary *indesignBackgroundAttributes = nil;
static NSMutableDictionary *indesignForegroundAttributes = nil;
- (void)drawRect:(NSRect)frame {
NSString *string = #"Got stroke?";
if (regularAttributes == nil) {
regularAttributes = [[NSMutableDictionary
dictionaryWithObjectsAndKeys:
[NSFont systemFontOfSize:64.0],NSFontAttributeName,
[NSColor whiteColor],NSForegroundColorAttributeName,
[NSNumber numberWithFloat:-5.0],NSStrokeWidthAttributeName,
[NSColor blackColor],NSStrokeColorAttributeName, nil] retain];
}
if (indesignBackgroundAttributes == nil) {
indesignBackgroundAttributes = [[NSMutableDictionary
dictionaryWithObjectsAndKeys:
[NSFont systemFontOfSize:64.0],NSFontAttributeName,
[NSNumber numberWithFloat:-5.0],NSStrokeWidthAttributeName,
[NSColor blackColor],NSStrokeColorAttributeName, nil] retain];
}
if (indesignForegroundAttributes == nil) {
indesignForegroundAttributes = [[NSMutableDictionary
dictionaryWithObjectsAndKeys:
[NSFont systemFontOfSize:64.0],NSFontAttributeName,
[NSColor whiteColor],NSForegroundColorAttributeName, nil] retain];
}
[[NSColor grayColor] set];
[NSBezierPath fillRect:frame];
// draw top string
[string drawAtPoint:
NSMakePoint(frame.origin.x + 200.0, frame.origin.y + 200.0)
withAttributes:regularAttributes];
// draw bottom string in two passes
[string drawAtPoint:
NSMakePoint(frame.origin.x + 200.0, frame.origin.y + 140.0)
withAttributes:indesignBackgroundAttributes];
[string drawAtPoint:
NSMakePoint(frame.origin.x + 200.0, frame.origin.y + 140.0)
withAttributes:indesignForegroundAttributes];
}
#end
This produces the following output:
Now, it's not perfect, since the glyphs will sometimes fall on fractional boundaries, but, it certainly looks better than the default.
If performance is an issue, you could always look into dropping down to a slightly lower level, such as CoreGraphics or CoreText.
Just leave here my solution based on answer of #NSGod, result is pretty the same just having proper positioning inside UILabel
It is also useful when having bugs on iOS 14 when stroking letters with default system font (refer also this question)
Bug:
#interface StrokedTextLabel : UILabel
#end
/**
* https://stackoverflow.com/a/4468880/3004003
*/
#implementation StrokedTextLabel
- (void)drawTextInRect:(CGRect)rect
{
if (!self.attributedText) {
[super drawTextInRect:rect];
return;
}
NSMutableAttributedString *attributedText = self.attributedText.mutableCopy;
[attributedText enumerateAttributesInRange:NSMakeRange(0, attributedText.length) options:0 usingBlock:^(NSDictionary<NSAttributedStringKey, id> *attrs, NSRange range, BOOL *stop) {
if (attrs[NSStrokeWidthAttributeName]) {
// 1. draw underlying stroked string
// use doubled stroke width to simulate outer border, because border is being stroked
// in both outer & inner directions with half width
CGFloat strokeWidth = [attrs[NSStrokeWidthAttributeName] floatValue] * 2;
[attributedText addAttributes:#{NSStrokeWidthAttributeName : #(strokeWidth)} range:range];
self.attributedText = attributedText;
// perform default drawing
[super drawTextInRect:rect];
// 2. draw unstroked string above
NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
style.alignment = self.textAlignment;
[attributedText addAttributes:#{
NSStrokeWidthAttributeName : #(0),
NSForegroundColorAttributeName : self.textColor,
NSFontAttributeName : self.font,
NSParagraphStyleAttributeName : style
} range:range];
// we use here custom bounding rect detection method instead of
// [attributedText boundingRectWithSize:...] because the latter gives incorrect result
// in this case
CGRect textRect = [self boundingRectWithAttributedString:attributedText forCharacterRange:NSMakeRange(0, attributedText.length)];
[attributedText boundingRectWithSize:rect.size options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
// adjust vertical position because returned bounding rect has zero origin
textRect.origin.y = (rect.size.height - textRect.size.height) / 2;
[attributedText drawInRect:textRect];
}
}];
}
/**
* https://stackoverflow.com/a/20633388/3004003
*/
- (CGRect)boundingRectWithAttributedString:(NSAttributedString *)attributedString
forCharacterRange:(NSRange)range
{
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:[self bounds].size];
textContainer.lineFragmentPadding = 0;
[layoutManager addTextContainer:textContainer];
NSRange glyphRange;
// Convert the range for glyphs.
[layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
}
#end
Swift version
import Foundation
import UIKit
/// https://stackoverflow.com/a/4468880/3004003
#objc(MUIStrokedTextLabel)
public class StrokedTextLabel : UILabel {
override public func drawText(in rect: CGRect) {
guard let attributedText = attributedText?.mutableCopy() as? NSMutableAttributedString else {
super.drawText(in: rect)
return
}
attributedText.enumerateAttributes(in: NSRange(location: 0, length: attributedText.length), options: [], using: { attrs, range, stop in
guard let strokeWidth = attrs[NSAttributedString.Key.strokeWidth] as? CGFloat else {
return
}
// 1. draw underlying stroked string
// use doubled stroke width to simulate outer border, because border is being stroked
// in both outer & inner directions with half width
attributedText.addAttributes([
NSAttributedString.Key.strokeWidth: strokeWidth * 2
], range: range)
self.attributedText = attributedText
// perform default drawing
super.drawText(in: rect)
// 2. draw unstroked string above
let style = NSMutableParagraphStyle()
style.alignment = textAlignment
let attributes = [
NSAttributedString.Key.strokeWidth: NSNumber(value: 0),
NSAttributedString.Key.foregroundColor: textColor ?? UIColor.black,
NSAttributedString.Key.font: font ?? UIFont.systemFont(ofSize: 17),
NSAttributedString.Key.paragraphStyle: style
]
attributedText.addAttributes(attributes, range: range)
// we use here custom bounding rect detection method instead of
// [attributedText boundingRectWithSize:...] because the latter gives incorrect result
// in this case
var textRect = boundingRect(with: attributedText, forCharacterRange: NSRange(location: 0, length: attributedText.length))
attributedText.boundingRect(
with: rect.size,
options: .usesLineFragmentOrigin,
context: nil)
// adjust vertical position because returned bounding rect has zero origin
textRect.origin.y = (rect.size.height - textRect.size.height) / 2
attributedText.draw(in: textRect)
})
}
/// https://stackoverflow.com/a/20633388/3004003
private func boundingRect(
with attributedString: NSAttributedString?,
forCharacterRange range: NSRange
) -> CGRect {
guard let attributedString = attributedString else {
return .zero
}
let textStorage = NSTextStorage(attributedString: attributedString)
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: bounds.size)
textContainer.lineFragmentPadding = 0
layoutManager.addTextContainer(textContainer)
var glyphRange = NSRange()
// Convert the range for glyphs.
layoutManager.characterRange(forGlyphRange: range, actualGlyphRange: &glyphRange)
return layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
}
}

How to use NSString drawInRect to center text?

How can I draw a NSString centered within a NSRect?
I've started off with: (an extract from the drawRect method of my custom view)
NSString* theString = ...
[theString drawInRect:theRect withAttributes:0];
[theString release];
Now I'm assuming I need to set up some attributes. I've had a look through Apple's Cocoa documentation, but it's a bit overwhelming and can't find anything for how to add paragraph styles to the attributes.
Also, I can only find horizontal alignment, what about vertical alignment?
Vertical alignment you'll have to do yourself ((height of view + height of string)/2). Horizontal alignment you can do with:
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
[myString drawInRect:someRect withAttributes:attr];
This works for me for horizontal alignment
[textX drawInRect:theRect
withFont:font
lineBreakMode:UILineBreakModeClip
alignment:UITextAlignmentCenter];
Martins answer is pretty close, but it has a few small errors. Try this:
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
[style setAlignment:NSCenterTextAlignment];
NSDictionary *attr =
[NSDictionary dictionaryWithObject:style
forKey:NSParagraphStyleAttributeName];
[myString drawInRect:someRect withAttributes:attr];
[style release];
You'll have to create a new NSMutableParagraphStyle (instead of using the default paragraph style as Martin suggested) because [NSMutableParagraphStyle defaultParagraphStyle] returns an NSParagraphStyle, which doesn't have the setAlignment method. Also, you don't need the string #"NSParagraphStyleAttributeName"—just NSParagraphStyleAttributeName.
This works for me:
CGRect viewRect = CGRectMake(x, y, w, h);
UIFont* font = [UIFont systemFontOfSize:15];
CGSize size = [nsText sizeWithFont:font
constrainedToSize:viewRect.size
lineBreakMode:(UILineBreakModeWordWrap)];
float x_pos = (viewRect.size.width - size.width) / 2;
float y_pos = (viewRect.size.height - size.height) /2;
[someText drawAtPoint:CGPointMake(viewRect.origin.x + x_pos, viewRect.origin.y + y_pos) withFont:font];
[NSMutableParagraphStyle defaultParagraphStyle] won't work use:
[NSMutableParagraphStyle new]
also, it appears horizontal alignment only works for drawInRect, not drawAtPoint (ask me how I know :-)
For anyone interested in an iOS7+ adaptation, drop this in an NSString category:
- (void)drawVerticallyInRect:(CGRect)rect withFont:(UIFont *)font color:(UIColor *)color andAlignment:(NSTextAlignment)alignment
{
rect.origin.y = rect.origin.y + ((rect.size.height - [self sizeWithAttributes:#{NSFontAttributeName:font}].height) / 2);
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setAlignment:alignment];
[self drawInRect:rect withAttributes:#{
NSFontAttributeName : font,
NSForegroundColorAttributeName : color,
NSParagraphStyleAttributeName : style
}];
}
For iOS Swift,
To center String within the rectangle using the method draw(in:withAttributes:)
func drawInCenter(_ text: String, into rectangle: CGRect, with textFont: UIFont) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let rectangle = CGRect.zero
paragraphStyle.minimumLineHeight = rectangle.height / 2 + textFont.lineHeight / 2
let textAttributes = [NSAttributedString.Key.font: textFont,
NSAttributedString.Key.paragraphStyle: paragraphStyle] as [NSAttributedString.Key : Any]
(text as NSString).draw(in: rectangle, withAttributes: textAttributes)
}
Well, drawInRect is only good for basic text drawing (in other words, the system decides where to position your text) - often the only way to draw text positioned where you want is to simply calculate what point you want it at and use NSString's drawAtPoint:withAttributes:.
Also, NSString's sizeWithAttributes is hugely useful in any positioning math you end up having to do for drawAtPoint.
Good luck!
The correct answer is:
-drawInRect:withFont:lineBreakMode:alignment:
I also created a small category for vertical alignment. If you like to use it, go ahead :)
// NSString+NSVerticalAlign.h
typedef enum {
NSVerticalTextAlignmentTop,
NSVerticalTextAlignmentMiddle,
NSVerticalTextAlignmentBottom
} NSVerticalTextAlignment;
#interface NSString (VerticalAlign)
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font verticalAlignment:(NSVerticalTextAlignment)vAlign;
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode verticalAlignment:(NSVerticalTextAlignment)vAlign;
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment verticalAlignment:(NSVerticalTextAlignment)vAlign;
#end
// NSString+NSVerticalAlign.m
#import "NSString+NSVerticalAlign.h"
#implementation NSString (VerticalAlign)
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font verticalAlignment:(NSVerticalTextAlignment)vAlign {
switch (vAlign) {
case NSVerticalTextAlignmentTop:
break;
case NSVerticalTextAlignmentMiddle:
rect.origin.y = rect.origin.y + ((rect.size.height - font.pointSize) / 2);
break;
case NSVerticalTextAlignmentBottom:
rect.origin.y = rect.origin.y + rect.size.height - font.pointSize;
break;
}
return [self drawInRect:rect withFont:font];
}
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode verticalAlignment:(NSVerticalTextAlignment)vAlign {
switch (vAlign) {
case NSVerticalTextAlignmentTop:
break;
case NSVerticalTextAlignmentMiddle:
rect.origin.y = rect.origin.y + ((rect.size.height - font.pointSize) / 2);
break;
case NSVerticalTextAlignmentBottom:
rect.origin.y = rect.origin.y + rect.size.height - font.pointSize;
break;
}
return [self drawInRect:rect withFont:font lineBreakMode:lineBreakMode];
}
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment verticalAlignment:(NSVerticalTextAlignment)vAlign {
switch (vAlign) {
case NSVerticalTextAlignmentTop:
break;
case NSVerticalTextAlignmentMiddle:
rect.origin.y = rect.origin.y + ((rect.size.height - font.pointSize) / 2);
break;
case NSVerticalTextAlignmentBottom:
rect.origin.y = rect.origin.y + rect.size.height - font.pointSize;
break;
}
return [self drawInRect:rect withFont:font lineBreakMode:lineBreakMode alignment:alignment];
}
#end
The following snippet is useful for drawing a center text string using an Annotation custom image as a reference:
CustomAnnotation.h
#interface CustomAnnotation : MKAnnotationView
[...]
CustomAnnotation.m
[...]
- (void)drawRect:(CGRect)rect
{
ClusterAnnotation *associatedAnnotation = (CustomAnnotation *)self.annotation;
if (associatedAnnotation != nil)
{
CGContextRef context = UIGraphicsGetCurrentContext();
NSString *imageName = #"custom_image.png";
CGRect contextRect = CGRectMake(0, 0, 42.0, 42.0);
CGFloat fontSize = 14.0;
[[UIImage imageNamed:imageName] drawInRect:contextRect];
NSInteger myIntegerValue = [associatedAnnotation.dataObject.myIntegerValue integerValue];
NSString *myStringText = [NSString stringWithFormat:#"%d", myIntegerValue];
UIFont *font = [UIFont fontWithName:#"Helvetica-Bold" size:fontSize];
CGSize fontWidth = [myStringText sizeWithFont:font];
CGFloat yOffset = (contextRect.size.height - fontWidth.height) / 2.0;
CGFloat xOffset = (contextRect.size.width - fontWidth.width) / 2.0;
CGPoint textPoint = CGPointMake(contextRect.origin.x + xOffset, contextRect.origin.y + yOffset);
CGContextSetTextDrawingMode(context, kCGTextStroke);
CGContextSetLineWidth(context, fontSize/10);
CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
[myStringText drawAtPoint:textPoint withFont:font];
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
[myStringText drawAtPoint:textPoint withFont:font];
}
}