简体   繁体   English

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

[英]Fit custom view's frame to image drawn in drawRect

I am drawing a custom shape (pentagon) in drawRect of my custom UIView subclass: 我在自定义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];
}

When I add the custom drawing to my viewcontroller with: 当我使用以下命令将自定义图形添加到我的viewcontroller中时:

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

It ends up looking like: 最终看起来像:

在此处输入图片说明

Obviously I know I'm setting my frame to be 300 width/height, but is there a way to do a "size to fit" content on the view's frame after the contents have been drawn? 显然,我知道将框架的宽度/高度设置为300,但是在绘制内容后是否可以在视图的框架上进行“调整大小”内容?

If you keep a reference to your UIBezierPath , you can call bounds on it to get the bounding rectangle. 如果保留对UIBezierPath的引用,则可以对其调用bounds以获取边界矩形。 Override sizeToFit to use it: 覆盖sizeToFit以使用它:

- (void)sizeThatFits:(CGSize)size {
  CGSize newSize = CGSizeZero;
  newSize.width = MIN(size.width, CGRectGetMaxX(self.path.bounds));
  newSize.height = MIN(size.height, CGRectGetMaxY(self.path.bounds));
  return newSize;
}

You are kind of doing this backwards. 您有点倒退了。 The drawRect: method should draw its contents to fill its current bounds. drawRect:方法应绘制其内容以填充其当前边界。 In other words, don't hardcode any specific coordinates in drawRect: . 换句话说,不要在drawRect:任何特定坐标进行硬编码。 Calculate them properly based on the current bounds. 根据当前范围正确计算它们。

If you want the custom view to have a certain size, override the custom view's sizeToFit: method and return the appropriate size. 如果希望自定义视图具有特定大小,请覆盖自定义视图的sizeToFit:方法并返回适当的大小。

This way, when client code calls the custom view's sizeToFit method, the view will be sized based on the results of sizeToFit: . 这样,当客户端代码调用自定义视图的sizeToFit方法时,将根据sizeToFit:的结果调整视图的大小。 Then the drawRect: method will be called and it will draw to fill that size. 然后将调用drawRect:方法,它将进行绘制以填充该大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM