围绕CALayer面具的边界

时间:2017-03-31 15:38:27

标签: ios iphone graphics calayer

我将开始向您展示我需要最终产品的样子。

Final Product

我正在使用名为BAFluidView的cocoapod,它基本上模拟了容器中液体的运动。开发人员提供了guide(请参阅“用作图层”部分),其中显示了如何将一个蒙版添加到fluidView的图层以获得效果。

到目前为止,我可以使用我添加到项目中的任何UIImage来掩盖视图。但是,我在尝试在水滴的轮廓周围添加白色边框时遇到了问题,可以使用我能得到的任何帮助。

非常感谢!

1 个答案:

答案 0 :(得分:1)

这就是我所说的"蛮力"方法。创建一个用作蒙版的图像,并创建第二个图像作为轮廓。

注意:这些图像具有Alpha通道,因此除非/下载它们,否则可能不清楚。棋盘图像显示了它们在GIMP中的外观。

Mask Image(我从BAFluidView示例中获取):

enter image description here - enter image description here

白色轮廓图像(相信我,它在这里......只需点击下方):

enter image description here - enter image description here

和代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


    // load mask and outline
    UIImage *maskingImage = [UIImage imageNamed:@"blueDrop"];
    UIImage *outlineImage = [UIImage imageNamed:@"whiteOutlineThin"];

    // define rect equal to size of mask image
    CGRect rfv = CGRectMake(0, 0, maskingImage.size.width, maskingImage.size.height);

    // instantiate BAFluidView
    BAFluidView *fluidView = [[BAFluidView alloc] initWithFrame:rfv startElevation:@0.3];
    fluidView.fillColor = [UIColor colorWithHex:0x092eee];
    [fluidView fillTo:@0.90];
    [fluidView startAnimation];

    // if you want the "droplet" filled with a color
    //  fluidView.backgroundColor = [UIColor yellowColor];

    // instantiate a couple CALayer objects
    CALayer *maskingLayer = [CALayer layer];
    CALayer *outlineLayer = [CALayer layer];

    // set size to match mask
    maskingLayer.frame = rfv;
    outlineLayer.frame = rfv;

    // set mask layer content to mask image
    [maskingLayer setContents:(id)[maskingImage CGImage]];

    // give the mask layer to BAFluidView
    [fluidView.layer setMask:maskingLayer];

    // set outline layer content to outline image
    [outlineLayer setContents:(id)[outlineImage CGImage]];

    // create a "container" view
    UIView *containerView = [[UIView alloc] initWithFrame:rfv];

    // add the outline layer
    [containerView.layer addSublayer:outlineLayer];

    // add the BAFluidView
    [containerView addSubview:fluidView];

    // add the container view to the screen / main view
    [self.view addSubview:containerView];

    // position the view with constraints...
    containerView.translatesAutoresizingMaskIntoConstraints = NO;

    [containerView.widthAnchor constraintEqualToConstant:rfv.size.width].active = YES;
    [containerView.heightAnchor constraintEqualToConstant:rfv.size.height].active = YES;
    [containerView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES;
    [containerView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;

}

结果的屏幕上限:

enter image description here

你可以自动化它,让这个过程更加优雅"通过使用蒙版图像并通过代码动态生成轮廓,可以灵活地进行操作 - 例如,将蒙版图像缩小一点,然后使用原始大小的图像对其进行蒙版。