我可以绘制我的NSString,但是在绘制它们时我无法调整大小。我的drawRect:方法是:
- (void)drawRect:(CGRect)rect
{
NSArray *objectArray = [NSArray arrayWithObjects:[UIFont systemFontOfSize:80.0f], nil];
NSArray *keyArray = [NSArray arrayWithObjects:@"NSFontAttributeName", nil];
NSMutableDictionary *textAttributes = [NSMutableDictionary dictionaryWithObjects:objectArray forKeys:keyArray];
NSString *myTestString = @"Test String";
[textAttributes setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
[myTestString drawAtPoint:CGPointMake(20, 30) withAttributes:textAttributes];
[myTestString drawInRect:CGRectMake(50, 50, 500, 500) withAttributes:textAttributes];
NSLog(@"wrote %@ with %@", myTestString, textAttributes);
}
textAttributes看起来不错,并且字体信息返回为:
NSFontAttributeName = "<UICTFont: 0x14eeff40> font-family: \".HelveticaNeueInterface-M3\"; font-weight: normal; font-style: normal; font-size: 80.00pt"
我可以使用属性数组正确更改颜色,为什么这会导致文本为默认的10pt大小?
最佳答案
NSAttributedString是您想要的。 UICatalog示例代码提供了NSAttributedString用法的示例:
#pragma mark - UIPickerViewDataSource
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSMutableAttributedString *attrTitle = nil;
// note: for the custom picker we use custom views instead of titles
if (pickerView == self.myPickerView)
{
if (row == 0)
{
NSString *title;
if (component == 0)
title = [self.pickerViewArray objectAtIndex:row];
else
title = [[NSNumber numberWithInt:row] stringValue];
// apply red text for normal state
attrTitle = [[NSMutableAttributedString alloc] initWithString:title];
[attrTitle addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(0, [attrTitle length])];
}
}
return attrTitle;
}
iOS上的Stanford U MOOC课程(由Paul Hegarty和available on iTunes负责运行)在第4课中概述了NSAttributedString的用法。第5课还提供了NSAttributedString代码演示,您可以遵循。最后,github用户m2mtech发布了repositories of all code exercises and assignments for the course,您可以下载相关的项目文件here。
关于ios - 如何使用属性绘制NSString atPoint并调整大小?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21469384/