CALayer 蒙版周围的边框

Borders around a CALayer mask

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

我正在使用一个名为 BAFluidView 的椰子足类动物,它基本上可以模拟容器中流体的运动。开发人员提供了 guide(请参阅 "Use As a Layer" 部分),展示了如何将遮罩添加到 fluidView 的图层以获得效果。

到目前为止,我可以使用添加到项目中的任何 UIImage 来屏蔽 fluiview。然而,我在尝试在水滴轮廓周围添加白色边框时遇到了问题,我可以寻求任何帮助。

非常感谢!

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

注意:这些图像有 alpha 通道,因此您下载它们可能不清楚 unless/until。棋盘图像显示了它们在 GIMP 中的外观。

遮罩图像(我从 BAFluidView 示例中获取):

-

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

-

和代码:

- (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;

}

Screen-cap 结果:

您可以将其自动化,并使过程更加 "elegant" 和灵活,方法是仅使用蒙版图像并通过代码生成轮廓 on-the-fly - 将蒙版图像按比例放大一点点,然后用原始大小的图像遮盖它,例如。