代码之家  ›  专栏  ›  技术社区  ›  user1272965

UIView的层掩码为设置帧设置动画

  •  0
  • user1272965  · 技术社区  · 8 年前

    我想创建一个UIView子类来屏蔽自己,这样我添加到其中的任何子视图都会被一个圆裁剪。我想在IB中定义这个视图及其子视图,这样我就可以轻松地为子视图定义布局约束。到目前为止,我有以下几点。。。

    @interface BubbleView ()
    // eg: this is an example of a child view that would be "under" a mask
    @property(weak,nonatomic) IBOutlet UIImageView *imageView;
    @end
    
    @implementation BubbleView
    
    // not really sure if this kind of init is the right pattern, but it seems to work and 
    // I don't think this is my current problem??
    + (instancetype)bubbleViewFromNib {
        BubbleView *view = [[NSBundle mainBundle] loadNibNamed:@"BubbleView" owner:nil options:nil][0];
    
        UIImage *_maskingImage = [UIImage imageNamed:@"circlemask"];
        CALayer *maskingLayer = [CALayer layer];
        [view.layer addSublayer:maskingLayer];
    
        maskingLayer.contents = (__bridge id _Nullable)(_maskingImage.CGImage);
        view.layer.mask = maskingLayer;
    
        return view;
    }
    
    - (void)layoutSubviews {
        self.layer.mask.frame = self.bounds;
    }
    

    (注意:我在IB中给视图一个紫色,这样我可以看到发生了什么)

    - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        BubbleView *b = (BubbleView *)[self.view viewWithTag:222];
        //b.transform = CGAffineTransformScale(b.transform, 1.2, 1.2);
        b.frame = CGRectInset(b.frame, -30,-30);
    }
    

    遮罩做了一些奇怪的事情:它保持小的“跳跃”到视图的左上角,然后非常快地设置动画到正确的大小(大30,30)。 为什么会有动画?

    之前

    enter image description here

    enter image description here

    将NSLog放置在layoutSubviews中,我注意到它被调用了两次,这很奇怪,但仍然没有足够的时间来解释快速动画。

    此外,当我更改变换而不是帧时,它会完美地调整大小,没有动画。但我需要同时进行帧和变换更改。

    1 回复  |  直到 8 年前
        1
  •  0
  •   matt    8 年前

    设置层的可设置动画的特性时,除非该层是UIView的主层,否则默认为隐式动画。此外 frame 房地产只是 bounds position 属性。因此,永远不要设置层的 直接地始终设置 界限 你自己如果不需要动画,则需要关闭这些属性的隐式动画;最简单的方法是在当前CATTransaction中完全关闭它( setDisableActions true )但是有更微妙和精确的方法来完成同样的事情。