我在自定义 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];
}
它最终看起来像:
显然我知道我将我的框架设置为 300 宽度/高度,但是有没有办法在绘制内容后在 View 的框架上执行“大小适合”内容?
最佳答案
你有点倒退了。 drawRect:
方法应绘制其内容以填充其当前边界。换句话说,不要在 drawRect:
中硬编码任何特定坐标。根据当前边界正确计算它们。
如果您希望自定义 View 具有特定大小,请覆盖自定义 View 的 sizeToFit:
方法并返回适当的大小。
这样,当客户端代码调用自定义 View 的 sizeToFit
方法时, View 的大小将基于 sizeToFit:
的结果。然后将调用 drawRect:
方法并绘制以填充该大小。
关于ios - 使自定义 View 的框架适合在 drawRect 中绘制的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28218227/