使用另一个CALayer屏蔽CALayer [英] Masking a CALayer with another CALayer

查看:138
本文介绍了使用另一个CALayer屏蔽CALayer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用CALayers制作甜甜圈。一个CALayer将是一个大圆圈,另一个将是一个位于其中心的较小圆圈,将其遮盖。

I'm trying to make a donut shape with CALayers. One CALayer will be a large circle, the other one will be a smaller circle positioned in its center, masking it.

大圆圈显示正常,但每当我调用 circle.mask = circleMask; 时,视图显示为空。

The large circle displays fine, but whenever I call circle.mask = circleMask; then the view appears empty.

这是我的代码:

AriDonut.h

#import <UIKit/UIKit.h>

@interface AriDonut : UIView
-(id)initWithRadius:(float)radius;
@end

AriDonut.m

#import "AriDonut.h"
#import <QuartzCore/QuartzCore.h>

@implementation AriDonut

-(id)initWithRadius:(float)radius{
    self = [super initWithFrame:CGRectMake(0, 0, radius, radius)];
    if(self){

        //LARGE CIRCLE
        CALayer *circle = [CALayer layer];
        circle.bounds = CGRectMake(0, 0, radius, radius);
        circle.backgroundColor = [UIColor redColor].CGColor;
        circle.cornerRadius = radius/2;
        circle.position = CGPointMake(radius/2, radius/2);

        //SMALL CIRLCE
        CALayer *circleMask = [CALayer layer];
        circleMask.bounds = CGRectMake(0, 0, 10, 10);
        circleMask.cornerRadius = radius/2;
        circleMask.position = circle.position;

        //circle.mask = circleMask;

        [self.layer addSublayer:circle];

    }

    return self;
}

我试过设置大圆圈的超级层nil如下:

I've tried setting the large circle's superlayer nil like this:

CALayer *theSuper = circle.superlayer;
theSuper = nil;

但它没有什么区别。

我也尝试将Circle的 masksToBounds 属性设置为YES和NO,但它没有什么区别。

I also tried setting Circle's masksToBounds property to YES and NO, but it didn't make a difference.

有什么想法吗?

推荐答案

的确,因为@David表示当前(iOS 5.1)CALayer蒙版无法反转,如果您想使用它们将透明孔制作为简单的圆形CALayer,则会出现问题。

Indeed, as @David indicates the current (iOS 5.1) CALayer masks can't be reversed, which poses a problem if you want to use them to make a transparent hole a simple circular CALayer.

你可以做一个圆形的CALayer的 backgroundColor 透明,但给它一个 borderColor 和宽 borderWidth 。这是dunkin'代码:

What you can do to get a donut is make a circular CALayer's backgroundColor transparent, but give it a borderColor and a wide borderWidth. Here's the dunkin' code:

    CALayer *theDonut = [CALayer layer];
    theDonut.bounds = CGRectMake(0,0, radius, radius);
    theDonut.cornerRadius = radius/2;
    theDonut.backgroundColor = [UIColor clearColor].CGColor;

    theDonut.borderWidth = radius/5;
    theDonut.borderColor = [UIColor orangeColor].CGColor;

    [self.layer addSublayer:theDonut];

这篇关于使用另一个CALayer屏蔽CALayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆