ios - 使自定义 View 的框架适合在 drawRect 中绘制的图像

标签 ios objective-c drawrect uibezierpath

我在自定义 UIView 子类的 drawRect 中绘制自定义形状(五边形):

- (void)drawRect:(CGRect)rect {
    UIBezierPath *aPath = [UIBezierPath bezierPath];

    // Set the starting point of the shape.
    [aPath moveToPoint:CGPointMake(100.0, 0.0)];

    // Draw the lines.
    [aPath addLineToPoint:CGPointMake(200.0, 40.0)];
    [aPath addLineToPoint:CGPointMake(160, 140)];
    [aPath addLineToPoint:CGPointMake(40.0, 140)];
    [aPath addLineToPoint:CGPointMake(0.0, 40.0)];
    [aPath closePath];

    [[UIColor blackColor] setStroke];
    [[UIColor redColor] setFill];

    [aPath fill];
    [aPath stroke];
}

当我将自定义绘图添加到我的 View Controller 时:

- (void)viewDidLoad {
    [super viewDidLoad];
    PentagonView *pentagonView = [[PentagonView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
    [self.view addSubview:pentagonView];
}

它最终看起来像:

enter image description here

显然我知道我将我的框架设置为 300 宽度/高度,但是有没有办法在绘制内容后在 View 的框架上执行“大小适合”内容?

最佳答案

你有点倒退了。 drawRect: 方法应绘制其内容以填充其当前边界。换句话说,不要在 drawRect: 中硬编码任何特定坐标。根据当前边界正确计算它们。

如果您希望自定义 View 具有特定大小,请覆盖自定义 View 的 sizeToFit: 方法并返回适当的大小。

这样,当客户端代码调用自定义 View 的 sizeToFit 方法时, View 的大小将基于 sizeToFit: 的结果。然后将调用 drawRect: 方法并绘制以填充该大小。

关于ios - 使自定义 View 的框架适合在 drawRect 中绘制的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28218227/

相关文章:

ios - 是否可以在 UIImagePickerController 中以编程方式调用 didFinishPickingMediaWithInfo

javascript - 在 UIWebView 中设置超链接样式

ios - 使用 ARC 的 peoplePicker 内存泄漏

iphone - 树屋

c++ - 我可以从 C++ 程序中调用 Objective-C 类吗?

ios - NStimer 和 setNeedsDisplay

ios - 将 CLLocation 对象转换为 MKMapPoint 结构

ios - SearchBarController 谓词导致崩溃

ios - 按下按钮时更改自定义 UIButton (CoreGraphics) 的背景颜色

ios - 在 Swift for iOS 中沿圆形路径绘制文本