簡體   English   中英

iOS在子視圖中繪制文本

[英]IOS drawing text inside a subview

我試圖在子視圖上繪制文本,視圖看起來很好,但文本卻不行,這就是我正在做的,視圖具有黑色,文本具有白色,文本和其他方法給出的rect值:

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: sumText drawRect:中會自動為您創建圖形上下文drawRect:因此您可以繼續進行繪制。

但實際上,您可能只想使用UILabel

還有另一種方法可以實現您想要的。

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];

輸出為:

產量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM