【问题标题】:How can I have a UIView act like bounds to a CaLayer?我怎样才能让 UIView 像 CaLayer 的边界一样?
【发布时间】:2018-01-08 04:33:13
【问题描述】:

我有一个贝塞尔路径,我将其转换为 CALayer,然后添加到视图中。

我希望 UIView 的高度和宽度与 CALayer 形状完全一致。

myHTML = @"<html><body><svg height= \"400\" width= \"400\"><g><path d=\"M 20 20  C 30 30 40 40 50 50 M 50 50 C 60 70 80 70 60 50 \"  transform=\"translate(-20, -20)\" stroke = \"#000000\" fill=\"none\" stroke-width=\"5px\"></path></g></svg></body></html>";

    NSArray *test = [SVGBezierPath pathsFromSVGString:myHTML];
    for(SVGBezierPath *path in test) {
        // Create a layer for each path
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.path = path.CGPath;
        UIView *vw = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
        // Set its display properties
        layer.lineWidth   = 4;
        layer.strokeColor = [[UIColor blackColor] CGColor];
        layer.fillColor   = [[UIColor clearColor] CGColor];
        vw.center = self.view.center;
        [vw setBackgroundColor:[UIColor grayColor]];
        // Add it to the layer hierarchy
        [vw.layer addSublayer:layer];

        [self.view addSubview:vw];
    }

当我尝试这段代码时,我得到了这个

我试着给视图层的宽度和高度

vw = [[UIView alloc]initWithFrame:CGRectMake(vw.bounds.origin.x, vw.bounds.origin.y, layer.bounds.size.height, layer.bounds.size.width)];

然后视图消失,只有图层可见。

我想得到如下图所示的东西,我有调整大小视图和东西的代码,但需要让视图的边界恰好是视图的最大高度和最大宽度,如下所示。

【问题讨论】:

    标签: objective-c uiview calayer uibezierpath


    【解决方案1】:

    尝试将视图框架设置为路径边界框。假设 SVGBezierPath 是 UIBezierPath 的子类。

    // First create your UIView vw
    vw.bounds = CGRectMake(vw.bounds.origin.x, vw.bounds.origin.y,
                           path.bounds.size.width, path.bounds.size.height)];
    

    【讨论】:

    • 现在的视图更小了,CAShapeLayer 被切了一半
    • 对不起,宽度和高度弄混了。请再试一次!
    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 2013-08-25
    • 1970-01-01
    • 2013-01-08
    • 2015-09-23
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多