我试图通过 drawInRect:withAttributes:
方法将字符串放入矩形形式。官方文档写道:“在当前聚焦的 UIView 中的指定矩形内,使用给定属性的字体和其他显示特性绘制接收器。”
此操作应在按钮事件上完成。但这根本不起作用。什么也没显示。 我使用的代码:
- (IBAction)buttonPressed:(id)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];
}
是否有某种特定类型的区域可用于在矩形中绘制字符串?或者是否可以在我想要的矩形中绘制字符串?请帮助我更好地理解它!
最佳答案
But it doesn't work at all. Nothing is shown.
这是因为当您运行该代码时没有设置绘图上下文。您认为绘图是您可以随时进行的事情,但实际上绘图是您仅应在系统要求时才进行的事情。其他时候,你应该记住你要画什么,然后到时候再画。
什么时候是绘画的“时间”?当你的 View 的 -drawRect:
方法被调用时。由于您的方法是一个操作,因此看起来您可能正在尝试在 View Controller 中进行绘图。相反,您想要做的是继承 UIView
并重写 -drawRect:
来绘制您想要的内容。
关于ios - 在矩形中绘制 NSString 对象。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25388128/