我试图在子视图上绘制文本,视图显得很好而文本没有,这就是我在做什么,视图有黑色,文本有白色,文本和其他方法给出的rect值: / p>
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];}
我做错了什么?感谢
答案 0 :(得分:1)
drawInRect:withAttributes:
方法在当前图形上下文中绘制字符串。您尚未定义上下文,因此您的绘图无处可去。
如果您想自己绘制字符串,则应该继承UIView
,添加必需的属性(sumText
),并覆盖drawRect:
。在drawRect:
中自动为您创建图形上下文,以便您可以继续绘制。
但实际上,您可能只想使用UILabel
代替。
答案 1 :(得分:0)
还有另一种方法可以达到你想要的效果。
UILabel* lblText = [[UILabel alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
lblText.text = @"Hello World!";
lblText.backgroundColor = [UIColor blackColor];
lblText.textColor = [UIColor whiteColor];
[self.view addSubview:lblText];
输出是: