Core Text - Position of text is incorrect - ios

This is the first time I've used core graphics and text so could be doing something very simple thats incorrect. I've been reading the documentation to try and see where i'm going wrong but can't see it so wonder if someone can help me spot the issue.
I'm trying to draw a simple little banner of information at the top of the screen but the text i want to appear in the banner is not drawn in the correct place.
In my view i'm creating my control as follows:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.banner = [[Banner alloc] initWithFrame:CGRectMake(0,20,768,200)];
[self.view addSubview:self.banner];
}
The controls code is as follows:
#import <CoreText/CoreText.h>
#import "Banner.h"
#implementation Banner
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Get the graphics context.
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw the banner border.
CGContextSaveGState(context);
UIColor *strokeColor = [UIColor blackColor];
CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);
CGContextSetLineWidth(context, 5);
CGContextStrokeRect(context, CGRectMake(2,2,self.frame.size.width -4,100));
CGContextRestoreGState(context);
// Setup the text label & value.
NSString *addressLabelText = #"Address";
NSString *addressValue = #"123 Letsby Avenue\nSome Place\nSome City\nSome County\nSome Postcode";
UIFont *font = [UIFont fontWithName:#"Helvetica" size:14.0];
CGSize labelSize = [self getBoundsForString:addressLabelText usingFont:font];
CGSize valueSize = [self getBoundsForString:addressValue usingFont:font];
// So I want to Draw the label at X:10 Y:10 and the Value At X:65 Y:10
// So we get Something like:
// =============================
// || Address 123 letsby avenue
// || Some Place
// || Some City
// || Some County
// || Some Postcode
// =============================
CGRect labelBounds = CGRectMake(10,10,labelSize.width,labelSize.height);
// Move the address value over the margin width(10) + the label width + some spacing(5)
CGRect valueBounds = CGRectMake(10 + labelSize.width + 5, 10, valueSize.width, valueSize.height);
[self drawString: addressLabelText withFont: font inRect:labelBounds usingContext:context];
[self drawString: addressValue withFont: font inRect:valueBounds usingContext:context];
// The text hasn't drawn where i thought it should. Draw a rect there to make sure i had the right bounds
UIColor *rectFillColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:0.3];
CGContextSaveGState(context);
CGContextSetFillColorWithColor(context, [rectFillColor CGColor]);
CGContextFillRect(context, labelBounds);
CGContextFillRect(context, valueBounds);
CGContextRestoreGState(context);
//Hmm that is drawing in the right place. Whats going wrong with drawing the text.
[self setNeedsDisplay];
}
-(void) drawString:(NSString*) string withFont:(UIFont*)font inRect:(CGRect)rect usingContext:(CGContextRef) context
{
CGContextSaveGState(context);
// flipping the coordinate system.
CGContextTranslateCTM(context, 0, 200); // The control is rendered in a frame 200 high.
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
// Define the path we are going to draw the text on.
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, rect);
CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), (CFStringRef)string);
// Create the framesetter with the attributed string.
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
CFRelease(attrString);
// Create a frame.
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
// Draw the specified frame in the given context.
CTFrameDraw(frame, context);
CGContextRestoreGState(context);
CFRelease(frame);
CFRelease(path);
CFRelease(framesetter);
}
-(CGSize) getBoundsForString:(NSString *)string usingFont:(UIFont *)font
{
return [string boundingRectWithSize:CGSizeMake(999,999)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]
context:nil].size;
}
#end
The result of this is some blue rects drawn in the banner where i would expect the text to be but the text actually appears outside of the banner and I'm puzzled why.
https://www.dropbox.com/s/q2ap9tl4okaka49/Banner.png

I've found what seems to work for my code above... changing this:
-(void) drawString:(NSString*) string withFont:(UIFont*)font inRect:(CGRect)rect usingContext:(CGContextRef) context
{
CGContextSaveGState(context);
// flipping the coordinate system.
CGContextTranslateCTM(context, 0, 200); // The control is rendered in a frame 200 high.
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
to
-(void) drawString:(NSString*) string withFont:(UIFont*)font inRect:(CGRect)rect usingContext:(CGContextRef) context
{
CGContextSaveGState(context);
// flipping the coordinate system.
CGContextTranslateCTM(context, 0, rect.size.height+(2*rect.origin.y));
CGContextScaleCTM(context, 1.0, -1.0);
The line following line doesn't seem to change anything.
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
And changing this line:
CGContextTranslateCTM(context, 0, 200);
to
CGContextTranslateCTM(context, 0, rect.size.height+(2*rect.origin.y));
places the text correctly where i'd expect it to be.... using Xamarin and the equivalent c# I have to invert the result of the height + 2Y result :-S

Related

How can my custom UIView draw a clear background?

I need to make my own UITableViewCellAccessoryDisclosureIndicator so I can have custom colors. I need to set the background to clear. No matter what I try, I can't get the clearColor to work. When I change the CGContextSetFillColorWithColor line below to redColor, it's red. I've tried setting opaque and backgroundColor and then calling super drawRect with my fill code removed and with my fill code present, but it's still no good. I've also tried CGContextClearRect in various ways.
Here's the red color version from the simulator. I need the UIView to be clear so that the pretty background image shows through.
I'm not terribly concerned with scrolling performance because this table will have very few rows.
- (instancetype) init {
self = [super init];
if (!self) return nil;
// [self setOpaque:NO];
// [self setBackgroundColor:[UIColor clearColor]];
return self;
}
- (void)drawRect:(CGRect)rect {
// [super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
// my obviously silly/naive attempt at making the background clear
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); // redColor works
CGContextFillRect(context, rect);
// drawing code for chevron
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetLineWidth(context, 3.f);
CGContextSetLineJoin(context, kCGLineJoinMiter);
CGContextMoveToPoint(context, PADDING, PADDING);
CGContextAddLineToPoint(context, self.frame.size.width - PADDING, self.frame.size.height/2);
CGContextAddLineToPoint(context, PADDING, self.frame.size.height - PADDING);
CGContextStrokePath(context);
CGContextRestoreGState(context);
}
How about this?
self.contentView.opaque = NO;
self.backgroundColor = [UIColor clearColor];
Designated. Flippin. Initializers. What a waste of time.
UIView's designated initializer is initWithFrame. initWithFrame doesn't call init. Notice that I overrided init. I had assumed that initWithFrame would call init.
Here's what works (notice I don't have to paint the background even though I'm not calling super.drawRect):
- (instancetype) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (!self) return nil;
// assume decent defaults
[self setColor:[UIColor darkGrayColor]];
[self setBackgroundColor:[UIColor clearColor]];
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, [self color].CGColor);
CGContextSetLineWidth(context, 3.f);
CGContextSetLineJoin(context, kCGLineJoinMiter);
CGContextMoveToPoint(context, PADDING, PADDING);
CGContextAddLineToPoint(context, rect.size.width - PADDING, rect.size.height/2);
CGContextAddLineToPoint(context, PADDING, rect.size.height - PADDING);
CGContextStrokePath(context);
CGContextRestoreGState(context);
}

iOS make hole in UIView other shape than square

I have a UIView that draws different shapes. I can make a hole in my image to have it transparent, working fine, but the hole is only square,
//hole
CGRect holeRectValue = CGRectMake(300, 40, 80, 100);
CGRect holeRectIntersection = CGRectIntersection( holeRectValue, rect );
[[UIColor clearColor] setFill];
UIRectFill(holeRectIntersection);
Now I need to make the hole in the image but not as a rect, as the shape of my drawn figure,
Here is the code:
- (id)initWithFrame:(CGRect)frame forNode0:(CGPoint)node0 forNode1:(CGPoint)node1 fornode2:(CGPoint)node2 fornode3:(CGPoint)node3 fornode4:(CGPoint)node4 fornode5:(CGPoint)node5 fornode6:(CGPoint)node6 fornode7:(CGPoint)node7 fornode8:(CGPoint)node8 fornode9:(CGPoint)node9
{
self = [super initWithFrame:frame];
if (self) {
self.opaque = NO;
self.node0Pos = node0;
self.node1Pos = node1;
self.node2Pos = node2;
self.node3Pos = node3;
self.node4Pos = node4;
self.node5Pos = node5;
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
//bgnd
UIGraphicsBeginImageContext(self.frame.size);
[[UIImage imageNamed:#"cat.jpeg"] drawInRect:self.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[[UIColor colorWithPatternImage:image] setFill];
// Drawing code
UIRectFill(rect);
// Drawing code
//1. begin new path
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
//2. move to initial starting point
CGContextMoveToPoint(context, self.node0Pos.x, self.node0Pos.y);
//3. add lines defining shape
CGContextAddLineToPoint(context, self.node1Pos.x, self.node1Pos.y);
CGContextAddLineToPoint(context, self.node2Pos.x, self.node2Pos.y);
CGContextAddLineToPoint(context, self.node3Pos.x, self.node3Pos.y);
CGContextAddLineToPoint(context, self.node4Pos.x, self.node4Pos.y);
CGContextAddLineToPoint(context, self.node5Pos.x, self.node5Pos.y);
//4. optionally close path
CGContextClosePath(context);
CGColorRef color;
//5. draw path
color = [UIColor colorWithRed:1 green:0 blue:228/255.0f alpha:0.5].CGColor;
//CGContextSetFillColor(context, color);
CGContextSetFillColorWithColor(context, color);
CGContextDrawPath(context, kCGPathFill);
//
//hole
CGRect holeRectValue = CGRectMake(300, 40, 80, 100);
CGRect holeRectIntersection = CGRectIntersection( holeRectValue, rect );
[[UIColor clearColor] setFill];
UIRectFill(holeRectIntersection);
}
So how do I make the "hole" with my actual context path?
P.S. I was doing some masking, but it leaves a white line around the hole, so I need to avoid this.
[[UIColor clearColor] setFill];
UIRectFill(holeRectIntersection);
This doesn’t do anything—drawing with a clear color is effectively a no-op. What you most likely want to do is add the rectangle you’re trying to cut out as part of the path you’re creating, i.e. inserting a call to CGContextAddRect before your CGContextClosePath. See Filling a Path in the Quartz 2D Programming Guide.
I believe what you're looking for is the CALayer.mask property. To create a "hole", you would generate a CALayer object with an alpha channel in the shape of the hole you want to make, and then apply it to the view you want to punch the hole in.
In semi-pseudocode:
CALayer *holeMask;
UIView *myView;
//
// Build the holeMask object via whatever means,
// and set myView to the target view that you want
// to punch the hole in...
//
myView.layer.mask = holeMask

Draw Angled/Rotated MultiLine Text - Core Text + Core Graphics

After going through several blogs & forums I didn't find an appropriate solution for drawing inclined/angled text using core Text on a views context.
So here is how it goes.
I have a view whose - (void)drawRect:(CGRect)rect is invoked to draw a string (multi or single line text) on screen.
CODE:
- (void)drawRect:(CGRect)rect
{
NSString *text = #"This is some text being drawn by CoreText!\nAnd some more text on another line!";
//Core Text (Create Attributed String)
UIColor *textColor = [UIColor blackColor];
CGColorRef color = textColor.CGColor;
CTFontRef font = CTFontCreateWithName((CFStringRef) #"HelveticaNeue", 20.0, NULL);
CTTextAlignment theAlignment = kCTTextAlignmentLeft;
CFIndex theNumberOfSettings = 1;
CTParagraphStyleSetting theSettings[1] =
{
{ kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),
&theAlignment }
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(theSettings, theNumberOfSettings);
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
CFBridgingRelease(font), (NSString *)kCTFontAttributeName,
color, (NSString *)kCTForegroundColorAttributeName,
paragraphStyle, (NSString *) kCTParagraphStyleAttributeName,
nil];
NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:text attributes:attributesDict];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)stringToDraw);
//Create Frame
CGMutablePathRef path = CGPathCreateMutable();
CGAffineTransform transform = CGAffineTransformMakeScale(1, -1);
//First translate your image View according to transform
transform = CGAffineTransformTranslate(transform, 0, - self.bounds.size.height);
// Then whenever you want any point according to UIKit related coordinates apply this transformation on the point or rect.
CGRect frameText = CGRectMake(60, 100, 200, 200);
CGRect newRectForUIKit = CGRectApplyAffineTransform(frameText, transform);
CGPathAddRect(path, NULL, newRectForUIKit);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
CGContextTranslateCTM(ctx, 0, ([self bounds]).size.height );
CGContextScaleCTM(ctx, 1.0, -1.0);
//Draw Frame
CTFrameDraw(frame, ctx);
//Release all retained objects
CFRelease(path);
}
Output:
Apart from drawing text I want to add an angle to the entire drawn text. Something like this(Required output)
So how do I add an rotation angle to the drawn text in core text?
Note: 1)A single context can have multiple drawn text objects with their respective angles as shown below
I hope my question is clear.
Apply the rotation to the context before drawing the CTFrameRef into it.
Edit :
If you want multiple angles, you need to save/restore the graphics states, each time.
Something like :
- (void)drawRect:(CGRect)rect
{
NSString *text = #"This is some text being drawn by CoreText!\nAnd some more text on another line!";
//Core Text (Create Attributed String)
UIColor *textColor = [UIColor blackColor];
CGColorRef color = textColor.CGColor;
CTFontRef font = CTFontCreateWithName((CFStringRef) #"HelveticaNeue", 20.0, NULL);
CTTextAlignment theAlignment = kCTTextAlignmentLeft;
CFIndex theNumberOfSettings = 1;
CTParagraphStyleSetting theSettings[1] =
{
{ kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),
&theAlignment }
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(theSettings, theNumberOfSettings);
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
CFBridgingRelease(font), (NSString *)kCTFontAttributeName,
color, (NSString *)kCTForegroundColorAttributeName,
paragraphStyle, (NSString *) kCTParagraphStyleAttributeName,
nil];
NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:text attributes:attributesDict];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)stringToDraw);
//Create Frame
CGMutablePathRef path = CGPathCreateMutable();
CGRect frameText = CGRectMake(60, 100, 200, 200);
CGPathAddRect(path, NULL, frameText);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx); /* save Graphic State for context rotation */
// transform (rotate) context
CGAffineTransform transform = CGAffineTransformMakeTranslation(self.bounds.size.width / 2.f, self.bounds.size.height / 2.f);
CGFloat rotation = -M_PI / 2.f;
transform = CGAffineTransformRotate(transform,rotation);
transform = CGAffineTransformTranslate(transform,-self.bounds.size.width / 2.f, -self.bounds.size.height / 2.f);
CGContextConcatCTM(ctx, transform);
CGContextSaveGState(ctx);
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
CGContextTranslateCTM(ctx, 0, ([self bounds]).size.height );
CGContextScaleCTM(ctx, 1.0, -1.0);
//Draw Frame
CTFrameDraw(frame, ctx);
//Release all retained objects
CFRelease(path);
CGContextRestoreGState(ctx);
CGContextRestoreGState(ctx); /* restore Graphic State for context rotation */
CGContextSaveGState(ctx); /* save Graphic States for another drawing */
/* lets draw another string with different angle */
attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
CFBridgingRelease(CTFontCreateWithName((CFStringRef) #"HelveticaNeue", 14.0, NULL)), (NSString *)kCTFontAttributeName,
[UIColor yellowColor].CGColor, (NSString *)kCTForegroundColorAttributeName,
nil];
stringToDraw = [[NSAttributedString alloc] initWithString:#"another piece of text to drawn on same context with no angle" attributes:attributesDict];
framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)stringToDraw);
path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(60, -100, 200, 200));
frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CFRelease(path);
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
CGContextTranslateCTM(ctx, 0, ([self bounds]).size.height );
CGContextScaleCTM(ctx, 1.0, -1.0);
CTFrameDraw(frame, ctx);
/**
* #note don't forget to restore a previously saved GState, or this will be source of problems
*/
CGContextRestoreGState(ctx);
CFRelease(frame);
CFRelease(framesetter);
}

coretext shows text from bottom to top of textfield

I'm drawing a textfield and i've added a textfield into the UIView. The text is within a path. It draws correctly, but the content starts at the bottom and ends at the top. Is there a way to fix this?
Here's my code:
// Draw text into a circle using Core Text and Quartz
- (void) drawRect:(CGRect)rect
{
[super drawRect: rect];
CGContextRef context = UIGraphicsGetCurrentContext();
self.layer.rasterizationScale = [[UIScreen mainScreen] scale];
// Flip the context
CGContextTranslateCTM(context, 0, 3);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0f, -1.0f));
// Stroke that path
CGContextAddPath(context, backPath);
CGContextSetLineWidth(context, 1.0f);
//[[UIColor blackColor] setStroke];
CGContextStrokePath(context);
// Fill that path
CGContextAddPath(context, backPath);
[[UIColor whiteColor] setFill];
CGContextFillPath(context);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string);
CTFrameRef theFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, string.length),backPath, NULL);
CTFrameDraw(theFrame, context);
CFRelease(framesetter);
CFRelease(theFrame);
CFRelease(backPath);
}
This how I make the path:
- (id) initWithAttributedString: (NSAttributedString *) aString path: (vector<ofPoint>)paths
{
backPath = CGPathCreateMutable();
CGPathMoveToPoint(backPath, NULL, paths[0].x, paths[0].y); // Bottom left
for(int x=1; x< paths.size(); x++){
CGPathAddLineToPoint(backPath, NULL, paths[x].x,paths[x].y); // Bottom right
}
CGPathCloseSubpath(backPath);
if (!(self = [super initWithFrame:CGRectZero])) return self;
self.backgroundColor = [UIColor clearColor];
string = aString;
return self;
}
And to make the text field:
path.push_back(ofPoint(ofGetWidth()/4,ofGetHeight()/4));
// point to user
// path.push_back(ofPoint((position.x-(ofGetWidth()/4))/2,ofGetHeight()/4));
// point to right top
path.push_back(ofPoint(ofGetWidth()/4,ofGetHeight()/4));
// point to end x, pos y user
path.push_back(ofPoint((ofGetWidth()/4),(position.y-(ofGetHeight()/4))/2));
path.push_back(ofPoint((position.x-(ofGetWidth()/4))/2-100,(position.y-(ofGetHeight()/4))/2-100));
path.push_back(ofPoint((position.x-(ofGetWidth()/4))/2,(position.y-(ofGetHeight()/4))/2));
You are flipping the text matrix. Instead, flip the whole CTM:
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, self.bounds.size.height);

Drawing rotated text on iOS creates jumping characters

I am trying to draw slightly rotated text with Core Graphics on the iOS platform. Text renders fine when not rotating but the rendering system tries to lock onto pixels for rotated text.
For example: If you rotate a Core Graphics context by some small amount (like 2 degrees) and then draw text the individual characters will appear to jump up and down as Core Graphics locks the characters to the pixels (font hinting). I know that the text may become blurry if it would not lock onto the pixel grid but that's acceptable. Jumping characters are not. So how can I disable vertical font hinting? Hinting horizontal would be ok, but turning it all off is ok too.
Code for custom UIView:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
[self.backgroundColor setFill];
CGContextFillRect(context, rect);
CGContextSaveGState(context);
// rotate context
CGContextTranslateCTM(context, self.bounds.size.width / 2.0, self.bounds.size.width / 2.0);
CGContextRotateCTM(context, 2.0 * M_PI / 180.0);
CGContextTranslateCTM(context, -self.bounds.size.width / 2.0, -self.bounds.size.width / 2.0);
[[UIColor blackColor] setFill];
[self.title drawInRect:[self bounds] withFont:[UIFont systemFontOfSize:15.0]];
CGContextRestoreGState(context);
}
Result (not exactly of this code but similar, red lines inserted to guide to the "error"):
The only solution I have found is to get the actual Bezier paths of the glyphs with Core Text and draw those, which circumvents any vertical hinting. The following code excerpt is rather lengthy:
CGRect textRect = CGRectMake(0.0, 0.0, 300.0, 190.0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Flip coordinate system vertically.
CGContextSaveGState(context);
CGFloat rectHeight = textRect.size.height;
CGContextTranslateCTM(context, 0.0, rectHeight);
CGContextScaleCTM(context, 1.0f, -1.0f);
// Positive degrees because of flip.
CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(2.0 * M_PI/180.0);
CGContextConcatCTM(context, rotationTransform);
CGFloat pointSize = 15.0;
CTFontRef font = CTFontCreateUIFontForLanguage(kCTFontSystemFontType,
pointSize,
NULL);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
NSDictionary *initialAttributes = (
#{
(NSString *)kCTFontAttributeName : (__bridge id)font,
(NSString *)kCTForegroundColorAttributeName : (__bridge id)[UIColor blackColor].CGColor
}
);
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:[self string]
attributes:initialAttributes];
//
// For typesetting a frame, we should create a paragraph style.
// Includes fix for CTFramesetter’s wrong line spacing behavior.
// See Technical Q&A QA1698: “How do I work-around an issue where some lines
// in my Core Text output have extra line spacing?”
//
// Center alignment looks best when filling an ellipse.
CTTextAlignment alignment = kCTLeftTextAlignment;
CTLineBreakMode lineBreakMode = kCTLineBreakByWordWrapping;
// This is the leading in the historical sense, which is added to the point
// size but does not include it like the line height does.
CGFloat leading = 2.0;
// Still, for the fix we do need the line height.
CGFloat lineHeight = pointSize + leading;
CTParagraphStyleSetting paragraphStyleSettings[] =
{
{
kCTParagraphStyleSpecifierAlignment,
sizeof(alignment),
&alignment
},
{
kCTParagraphStyleSpecifierLineBreakMode,
sizeof(lineBreakMode),
&lineBreakMode
},
// These two specifiers fix the line spacing when set to line height.
{
kCTParagraphStyleSpecifierMinimumLineHeight,
sizeof(lineHeight),
&lineHeight
},
{
kCTParagraphStyleSpecifierMaximumLineHeight,
sizeof(lineHeight),
&lineHeight
}
// Very important: Do not set kCTParagraphStyleSpecifierLineSpacing too,
// or it will be added again!
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(
paragraphStyleSettings,
sizeof(paragraphStyleSettings) / sizeof(paragraphStyleSettings[0])
);
// Apply paragraph style to entire string. This cannot be done when the
// string is empty, by the way, because attributes can only be applied to
// existing characters.
NSRange stringRange = NSMakeRange(0, [attributedString length]);
[attributedString addAttribute:(NSString *)kCTParagraphStyleAttributeName
value:(__bridge id)(paragraphStyle)
range:stringRange];
// Create bezier path to contain our text.
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, textRect);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(attributedString));
// Range with length 0 indicates that we want to typeset until we run out of
// text or space.
CTFrameRef frame = CTFramesetterCreateFrame(
framesetter,
CFRangeMake(0, 0),
path,
NULL
);
CFArrayRef lines = CTFrameGetLines(frame);
CFIndex lineCount = CFArrayGetCount(lines);
CFRange range = CFRangeMake(0, 0);
CGPoint lineOrigins[lineCount];
CTFrameGetLineOrigins(frame, range, lineOrigins);
for (NSUInteger lineIndex = 0; lineIndex < lineCount; ++lineIndex)
{
CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
CGPoint lineOrigin = lineOrigins[lineIndex];
CFArrayRef runs = CTLineGetGlyphRuns(line);
CFIndex runCount = CFArrayGetCount(runs);
for (NSUInteger runIndex = 0; runIndex < runCount; ++runIndex)
{
CTRunRef run = CFArrayGetValueAtIndex(runs, runIndex);
CFIndex glyphCount = CTRunGetGlyphCount(run);
CGGlyph glyphBuffer[glyphCount];
CTRunGetGlyphs(run, range, glyphBuffer);
CGPoint positionsBuffer[glyphCount];
CTRunGetPositions(run, range, positionsBuffer);
for (NSUInteger glyphIndex = 0; glyphIndex < glyphCount; ++glyphIndex)
{
CGGlyph glyph = glyphBuffer[glyphIndex];
CGPoint position = positionsBuffer[glyphIndex];
CGAffineTransform positionTransform = CGAffineTransformMakeTranslation(lineOrigin.x + position.x,
lineOrigin.y + position.y);
CGPathRef glyphPath = CTFontCreatePathForGlyph(font, glyph, &positionTransform);
CGContextAddPath(context, glyphPath);
}
}
}
CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
CGContextFillPath(context);
CFRelease(font);
CFRelease(framesetter);
// Use specialized release function when it exists.
CGPathRelease(path);
CGContextRestoreGState(context);

Resources