简体   繁体   中英

Swift: Add image to CALayer returns black

Very simply, I'm trying to add an image to a CALayer as a watermark on the video. I have done this on projects in the past and it has worked but for some reason it's consistently returning a black image on my current project.

Here is code:

  • I've unwrapped 'logo' to ensure it is valid

  • I've set the background to green. Currently the frame is filled black (not green), so I assume it is returning the image, but rendering black for some reason.

     if let logo = options.logoImage { let layer = CALayer() animationLayer.addSublayer(layer) layer.frame = CGRect(x: 0, y: 0, width: 300, height: 300) layer.backgroundColor = UIColor.green.cgColor layer.contents = logo.cgImage layer.contentsGravity =.resizeAspect }

I think you forgot to set your layer to the mask property:

layer.mask = imageSubLayer // or whatever it is called

So it would look something like this:


if let logo = options.logoImage {
      let layer = CALayer()
      animationLayer.addSublayer(layer)
      layer.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
      layer.backgroundColor = UIColor.green.cgColor
      layer.contents = logo.cgImage
      layer.mask = animationLayer
      layer.contentsGravity = .resizeAspect
  }


Edit:

CALayer `s are very transient and doesn't work properly outside of animations:

I tried to reproduce what you did (I just assumed you created your animationLayer the same I did):

  var animationLayer: CALayer = {
        let l = CALayer()
        l.contentsGravity = kCAGravityResizeAspect
        return l
    }()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM