【问题标题】:iOS How to draw text in UIViewControlleriOS 如何在 UIViewController 中绘制文本
【发布时间】:2014-05-28 23:57:13
【问题描述】:

我现在感觉很愚蠢。

我正在尝试在 UIViewController 上绘制文本。

我正在使用 Xcode 5 并从一个简单的单页项目开始,除了将这段代码添加到 ViewController.m 之外什么也没做:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    CGRect myRect=CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height);
    UIFont *myFont=[UIFont fontWithName:@"Helvetica" size:50];

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentRight;

    NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
    [attributes setObject:myFont forKey:NSFontAttributeName];
    [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
    [attributes setObject:[NSNumber numberWithFloat:4] forKey:NSStrokeWidthAttributeName];
    [attributes setObject:[UIColor whiteColor] forKey:NSStrokeColorAttributeName];
    [@"test" drawInRect:myRect withAttributes:attributes];

    // draw fill
    [attributes removeObjectForKey:NSStrokeWidthAttributeName];
    [attributes removeObjectForKey:NSStrokeColorAttributeName];
    [attributes setObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
    [@"test" drawInRect:myRect withAttributes:attributes];
}

它运行没有错误,但不产生任何文本 - 为什么?

【问题讨论】:

  • 您是否只是将其作为学习练习(如果是这样对您有好处)?否则,您可以在视图中添加 UILabel 并让它负责绘制您的文本。
  • 是的,正在努力学习 - 我在使用 UILabel 裁剪 Descenders 字体时遇到了麻烦,所以我想看看我是否可以自己绘制文本并消除这些问题。

标签: ios objective-c uivewcontroller


【解决方案1】:

drawInRect 方法不适用于UIViewController。该方法是 UIView 方法,并且仅当您的类是 UIView 类或子类时才有效。

因此,如上所述,您只需在 UILabel 上设置文本属性,然后将它们显示在屏幕上您喜欢的任何位置。它应该给你同样的效果。或者,您可以尝试将子类更改为 UIView,但这可能需要对您的代码进行比您想要的更多的修改。

【讨论】:

  • 那么,如果我想在我的 UIViewController 中使用自动创建的 View 会起作用吗?如果是这样,我将如何在视图中使用 Rect?或者我可以添加一个 ImageView 吗?
  • 我没有运气使用自动创建的视图,例如self.view,或带有drawInRect 方法的UIImageView。您可以使用 Core Graphics 在UIImageView 上进行一些绘图,但这可能不是您正在寻找的绘图文本。
【解决方案2】:

要添加到 tfrank377,您可以使用类似

的方式以编程方式添加标签
   UILabel *addLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
   [self.view addSubview:addLabel];
   addLabel.text = @"Hello World";

这将在您的 UIView 上显示文本。

【讨论】:

  • 谢谢,但由于上述其他错误,我正在尝试除 UILabels 之外的其他内容。
  • 你能举一个下降的例子吗?
  • 当然 - 这是我问的另一个问题。请注意,重点是在问题消失之前不要缩小字体 - 重点是尽可能显示最大的字体...stackoverflow.com/questions/22897158/…
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 2012-07-21
  • 2020-01-30
  • 2014-02-11
  • 1970-01-01
  • 2011-10-28
  • 2021-05-11
  • 1970-01-01
相关资源
最近更新 更多