IOS 在 subview 中绘制文本

标签 ios objective-c

我试图在 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/

相关文章:

ios - 我们可以在 iOS 上读取无线数据权限吗?

objective-c - 如何在 tabbarcontroller 中制作 View 的 uiscrollview?

iOS Swift On Tab 离开功能

ios - UIButton 选中状态改变图片

iOS Swift MKLocalSearchRequest

ios - UISlider 的 Avplayer 问题

objective-c - 仅显示 uiimage 的一部分

ios - 空值上的 NSDateFormatter dateFromString

objective-c - 在 Objective-C 中处理大数字?

ios - 点击自定义 UIView 会触发错误的选择器