我发现如何绘制旋转的文本用的NSString drawInRect这个答案:,但我不知道它是如何工作的,因为它只是有点为我工作: https://discussions.apple.com/thread/1779814?start=0&tstart = 0
我的代码如下所示:
CGContextSaveGState(context);
CGContextDrawLinearGradient(context, gradient, CGPointMake(0, centY - halfWidth), CGPointMake(0, centY + halfWidth), 0);
// Add text
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
NSString *str = @"some test string";
CGAffineTransform transform1 = CGAffineTransformMakeRotation(M_PI/4);
CGContextConcatCTM(context, transform1);
CGContextTranslateCTM(context, 0, 0);
UIFont *font = [UIFont systemFontOfSize:16.0];
[str drawInRect:CGRectMake(0, 0, 200, 100) withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UIBaselineAdjustmentNone];
所以,当我用这个,我看到文本被绘制在x轴下方45度。 我想沿着我的LinearGradient垂直绘制文本。 所以我想我能做到这一点,通过使用M_PI / 2为90度。 我没有看到我的文字虽然。 我曾尝试不同的变换的旋转,只有一些看起来像M_PI / 4和M_PI / 8的工作。 我认为,如果我用-M_PI / 4它将有文本45度的x轴和M_PI / 2将是x轴低于90度以上。 但这两种转了什么。
有什么想法吗? 谢谢。
Answer 1:
我认为,这是怎么回事,是因为它通过旋转在原点旋转的情况下,你旋转视图之外的文本的位置。
你旋转后,你需要做一个平移上下文回视图。 在下面的例子中,我逆时针旋转90度的范围内。 然后,我翻译的上下文的TX高度的距离。
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Create the gradient
CGColorRef startColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0].CGColor;
CGColorRef endColor = [UIColor colorWithRed:200.0/255.0 green:200.0/255.0 blue:200.0/255.0 alpha:1.0].CGColor;
NSArray *colors = [NSArray arrayWithObjects:(id)startColor, (id)endColor, nil];
CGFloat locations[] = { 0.0, 1.0 };
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef) colors, locations);
CGContextDrawLinearGradient(context, gradient, CGPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y), CGPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height), 0);
// Create text
CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
NSString *string = @"some test string";
UIFont *font = [UIFont systemFontOfSize:16.0];
// Rotate the context 90 degrees (convert to radians)
CGAffineTransform transform1 = CGAffineTransformMakeRotation(-M_PI_2);
CGContextConcatCTM(context, transform1);
// Move the context back into the view
CGContextTranslateCTM(context, -rect.size.height, 0);
// Draw the string
[string drawInRect:rect withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
// Clean up
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
CGContextRestoreGState(context);
}
需要注意的是,你还可以得到的字符串将如何呈现的尺寸,可以在做计算的文本的对齐方式帮助。
CGSize stringSize = [string sizeWithFont:font];
Answer 2:
我解决下一个方式这个问题。
1)声明上的NSString类别
@interface NSString (NMSchemeItemDraw)
-(void) drawWithBasePoint:(CGPoint)basePoint
andAngle:(CGFloat)angle
andFont:(UIFont*)font;
@end
这个类别将绘制文本与给定的中心点,在一行中,并用给定的字体和角度。
2)这一类的实施是看起来像:
@implementation NSString (NMSchemeItemDraw)
-(void) drawWithBasePoint:(CGPoint)basePoint
andAngle:(CGFloat)angle
andFont:(UIFont *)font{
CGSize textSize = [self sizeWithFont:font];
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform t = CGAffineTransformMakeTranslation(basePoint.x, basePoint.y);
CGAffineTransform r = CGAffineTransformMakeRotation(angle);
CGContextConcatCTM(context, t);
CGContextConcatCTM(context, r);
[self drawAtPoint:CGPointMake(-1 * textSize.width / 2, -1 * textSize.height / 2)
withFont:font];
CGContextConcatCTM(context, CGAffineTransformInvert(r));
CGContextConcatCTM(context, CGAffineTransformInvert(t));
}
@end
3)现在,我可以在我的使用[UIView drawRect:]
方法。 例如,在接下来的方式:
-(void)drawRect:(CGRect)rect{
NSString* example = @"Title";
[example drawWithBasePoint:CGPointMake(0.0f, 0.0f)
andAngle:M_PI
andFont:[UIFont boldSystemFontOfSize:16.0]];
}
Answer 3:
Here'a KoNEW的回答的更新和简化版本。 它保留作为奖金图形上下文的状态。 这也是一个简单的功能,而不是一个字符串扩展。
func drawRotatedText(_ text: String, at p: CGPoint, angle: CGFloat, font: UIFont, color: UIColor) {
// Draw text centered on the point, rotated by an angle in degrees moving clockwise.
let attrs = [NSFontAttributeName: font, NSForegroundColorAttributeName: color]
let textSize = text.size(attributes: attrs)
let c = UIGraphicsGetCurrentContext()!
c.saveGState()
// Translate the origin to the drawing location and rotate the coordinate system.
c.translateBy(x: p.x, y: p.y)
c.rotate(by: angle * .pi / 180)
// Draw the text centered at the point.
text.draw(at: CGPoint(x: -textSize.width / 2, y: -textSize.height / 2), withAttributes: attrs)
// Restore the original coordinate system.
c.restoreGState()
}
Answer 4:
KoNew的解决方案在斯威夫特:
extension NSString {
func drawWithBasePoint(basePoint:CGPoint, angle:CGFloat, font:UIFont) {
var attrs: NSDictionary = [
NSFontAttributeName: font
]
var textSize:CGSize = self.sizeWithAttributes(attrs as [NSObject : AnyObject])
// sizeWithAttributes is only effective with single line NSString text
// use boundingRectWithSize for multi line text
var context: CGContextRef = UIGraphicsGetCurrentContext()
var t:CGAffineTransform = CGAffineTransformMakeTranslation(basePoint.x, basePoint.y)
var r:CGAffineTransform = CGAffineTransformMakeRotation(angle)
CGContextConcatCTM(context, t)
CGContextConcatCTM(context, r)
self.drawAtPoint(CGPointMake(-1 * textSize.width / 2, -1 * textSize.height / 2), withAttributes: attrs as [NSObject : AnyObject])
CGContextConcatCTM(context, CGAffineTransformInvert(r))
CGContextConcatCTM(context, CGAffineTransformInvert(t))
}
}
使用方法:
let fieldFont = UIFont(name: "Helvetica Neue", size: 14)
myNSString.drawWithBasePoint(CGPointMake(bounds.width/2, bounds.height/2), angle: CGFloat(-M_PI_2), font: fieldFont!)
Answer 5:
感谢为这个职位,和克里斯的回答 ,和的Arkadiusz的另一个职位的答案 。
最后,我解决一个这个问题UILabel
子类,命名MyVerticalLabel
,并使其利用垂直文本。
@implementation MyVerticalLabel
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform transform = CGAffineTransformMakeRotation(-M_PI_2);
CGContextConcatCTM(context, transform);
CGContextTranslateCTM(context, -rect.size.height, 0);
// The drawing rect should be applied with transform to.
CGRect newRect = CGRectApplyAffineTransform(rect, transform);
newRect.origin = CGPointZero;
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = self.lineBreakMode;
textStyle.alignment = self.textAlignment;
// Apply current label attributes for drawing function.
NSDictionary *attributeDict =
@{
NSFontAttributeName : self.font,
NSForegroundColorAttributeName : self.textColor,
NSParagraphStyleAttributeName : textStyle,
};
[self.text drawInRect:newRect withAttributes:attributeDict];
}
@end
文章来源: Drawing rotated text with NSString drawInRect