【问题标题】:How to add shadow to UIImageView itself instead of its layer如何将阴影添加到 UIImageView 本身而不是其图层
【发布时间】:2018-05-14 17:53:58
【问题描述】:

我正在使用此方法向 UIImageView 添加阴影:

extension UIImageView {
    public func applyShadow()
        layer.shadowColor = UIColor.gray.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 0)
        layer.shadowOpacity = 0.2
        layer.shadowRadius = 8.0
        layer.masksToBounds = false
    }
}

我希望内容模式为.scaleAspectFit。但是,当我设置它时,layer 的框架与UIImageView 的框架不同,但我希望将阴影应用于UIImageView 的框架。我怎样才能做到这一点?

【问题讨论】:

  • 您发布的代码确实将阴影应用于UIImageView 的框架。听起来您想将阴影应用于图像视图中的缩放图像,而不是图像视图。
  • 不,正好相反。最初图像被拉伸并且阴影在我想要的位置,但是当我使用 .scaleAspectFit 时,图像变得更窄,阴影拥抱缩小的图像而不是原始帧。

标签: ios swift layer shadow


【解决方案1】:

解决方案是将我的UIImageView 的背景颜色设置为白色。如果没有颜色设置,图像的左右两侧就没有内容,因此阴影在.scaleAspectFit 图像上塌陷。使用颜色集后,阴影将应用于实际帧。

【讨论】:

    【解决方案2】:

    你必须通过用阴影爬行新图像来添加阴影来成像它的自我

    extension UIImageView {
    
        func addShadowToImageNotLayer(blurSize: CGFloat = 8.0){
    
            let shadowColor = UIColor(white:0.0, alpha:0.8).cgColor
    
            guard let image = self.image else {return}
    
            let context = CGContext(data: nil,
                                    width: Int(image.size.width + blurSize),
                                    height: Int(image.size.height + blurSize),
                                    bitsPerComponent: image.cgImage!.bitsPerComponent,
                                    bytesPerRow: 0,
                                    space: CGColorSpaceCreateDeviceRGB(),
                                    bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
    
            context.setShadow(offset: CGSize(width: blurSize/2,height: -blurSize/2),
                              blur: blurSize,
                              color: shadowColor)
            context.draw(image.cgImage!,
                         in: CGRect(x: 0, y: blurSize, width: image.size.width, height: image.size.height),
                         byTiling:false)
    
            self.image = UIImage(cgImage: context.makeImage()!)
    
        }
    }
    

    二手:

     UIImageView().addShadowToImageNotLayer(blurSize: 20)
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      相关资源
      最近更新 更多