OGeek|极客世界-中国程序员成长平台

标题: ios - 在一个 Rectangle 中绘制一个 NSString 的对象。 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 08:56
标题: ios - 在一个 Rectangle 中绘制一个 NSString 的对象。

我正在尝试通过 drawInRect:withAttributes: 方法将字符串放入矩形。官方文档写道:“在当前聚焦的 UIView 的指定矩形内,用给定属性的字体和其他显示特征绘制接收器。”

这个 Action 应该在一个按钮事件上完成。但它根本不起作用。什么都没有显示。 我使用的代码:

- (IBAction)buttonPressedid)sender
{
    // some area on the top (a part of UIView)
    CGRect rect = CGRectMake(50, 50, 100, 100);

    // my text
    NSString *str = @"Eh, what's wrong with this code?";

    // crappy attributes
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:8]};

    // and finally passing a message
    [str drawInRect:rect withAttributes:attributes];
}

是否有特定类型的区域可用于在矩形中绘制字符串?或者是否可以在我想要的矩形中绘制一个字符串?请帮助我更好地理解它!



Best Answer-推荐答案


But it doesn't work at all. Nothing is shown.

这是因为在您运行该代码时没有设置绘图上下文。您将绘图视为您可以随时做的事情,但实际上绘图是您应该只在系统要求您时才应该做的事情。其他时候,你应该记住你想画什么,到时候再画。

绘画的“时间”是什么时候?这是调用 View 的 -drawRect: 方法的时候。由于您的方法是一个 Action ,看起来您可能正在尝试在 View Controller 中进行绘图。你想要做的是继承 UIView 并覆盖 -drawRect: 来绘制你想要的东西。

关于ios - 在一个 Rectangle 中绘制一个 NSString 的对象。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25388128/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4