我试图在 subview 上绘制文本, View 显示正常但文本不是,这就是我正在做的, View 有黑色,文本有白色,其他方法给出的文本和矩形值:
NSString* sumText = [[NSString alloc]initWithFormat:@"%0.1f",sum];
CGRect textRect = CGRectMake(chartLocation.x+chartLength+10,
chartLocation.y,
20,
20);
[self drawTextRect:sumText inRect:textRect];
-(void)drawTextRect:(NSString *)sumText inRect:(CGRect)textRect {
UIFont* font=[UIFont fontWithName:@"Arial" size:(20/2)];
UIColor* textColor = [UIColor whiteColor];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle]mutableCopy];
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary* stringAttr=@{NSFontAttributeName:font,NSForegroundColorAttributeName:textColor,NSParagraphStyleAttributeName:paragraphStyle};
UIView* textView =[[UIView alloc] initWithFrame:textRect];
textView.backgroundColor = [UIColor blackColor];
[sumText drawInRect:textRect withAttributes:stringAttr];
[self.view addSubview:textView];}
我做错了什么吗?谢谢
最佳答案
drawInRect:withAttributes:
方法在当前图形上下文 中绘制字符串。您尚未定义上下文,因此您的绘图无处可去。
如果你想自己绘制字符串,你应该继承UIView
,添加所需的属性(sumText
),并覆盖drawRect:
.在 drawRect:
中自动为您创建一个图形上下文,因此您可以继续绘制。
但实际上,您可能只想改用 UILabel
。
关于IOS 在 subview 中绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29553515/