您可以使用CoreText(獲取字形)和CoreGraphics(繪製CGGlyphs)來繪製垂直文本。 一個簡單的示例,這是隻照顧一個字體屬性(手柄的有效範圍爲每個屬性,如果要處理不同的字體,字體大小等)
#import "NSAttributedString+VerticalDrawing.h"
@implementation TestView
- (void)drawRect:(CGRect)rect
{
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:@"This is a vertical text"
attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14.]}];
[aString drawVerticalAtPoint:CGPointMake(10, 10)];
}
@end
@implementation NSAttributedString (VerticalDrawing)
- (void)drawVerticalAtPoint:(CGPoint)location
{
UIFont *font = [[self attributesAtIndex:0 effectiveRange:NULL] objectForKey:NSFontAttributeName];
NSUInteger myLength = [self length];
CTFontRef ctfont = CTFontCreateWithName((CFStringRef)[font fontName], [font pointSize], NULL);
CGGlyph *glyphs = malloc(sizeof(CGGlyph) * myLength);
UniChar *characters = malloc(sizeof(UniChar) * myLength);
CGSize *advances = malloc(sizeof(CGSize) * myLength);
[[self string] getCharacters:characters range:NSMakeRange(0,myLength)];
CTFontGetGlyphsForCharacters(ctfont, characters, glyphs, myLength);
CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, glyphs, advances, myLength);
free(characters);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFontRef cgfont = CTFontCopyGraphicsFont(ctfont, NULL);
CGContextSetFont(ctx, cgfont);
CGContextSetFontSize(ctx, CTFontGetSize(ctfont));
CGAffineTransform textMatrix = CGAffineTransformMakeTranslation(location.x, location.y);
textMatrix = CGAffineTransformScale(textMatrix, 1, -1);
CGContextSetTextMatrix(ctx, textMatrix);
CGFloat lineHeight = CTFontGetAscent(ctfont) + CTFontGetDescent(ctfont) + CTFontGetLeading(ctfont);
location.y = -CTFontGetAscent(ctfont);
CGFloat maxAdvance = 0.;
NSUInteger i;
for (i = 0; i < myLength; i++)
maxAdvance = MAX(maxAdvance, advances[i].width);
for (i = 0; i < myLength; i++)
{
location.x = (maxAdvance - advances[i].width) * 0.5;
CGContextShowGlyphsAtPositions(ctx, &glyphs[i], &location, 1);
location.y -= lineHeight;
}
free(glyphs);
free(advances);
CGFontRelease(cgfont);
CFRelease(ctfont);
}
@end
![sample](https://i.stack.imgur.com/yaNVw.png)
你想繪製或使用默認的'UILabel'?這可能是'UILabel'.. – Mani
你試過characterwarp – codercat
@iMani我寧願繪製,但我可能能夠使用'UILabel'。 – Benjohn