且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在swift3.0.1阴影中同时给一个imageView带圆角

更新时间:2023-01-05 14:50:37

这是我的解决方案

基本思路:

  1. 使用一个额外的视图(比如 AView)作为图像视图的超级视图(对于那些你愿意使用阴影的视图)并将该视图类分配给 DGShadoView
  2. 将图像视图从左侧、右侧、顶部和底部固定到 AView(即超级视图),常量 5
  3. AView 的背景颜色设置为 清晰颜色 来自 storybosrd 的属性检查器,这很重要
  1. Use an Extra view (say AView) as super view of image view (to those views on which you are willing to have shado) and assign that view class to DGShadoView
  2. Pin Image view to AView (that super view)from left, right, top and bottom with constant 5
  3. Set back ground color of the AView to clear color from storybosrd's Property inspector this is important

内部想法: 这里我们在 Aview 上几乎在边框上使用贝塞尔路径,并将所有圆角属性和阴影属性设置为该路径,然后我们将目标图像视图放置在在那条路径中

@IBDesignable
class DGShadoView:UIView {

override func draw(_ rect: CGRect) {
    self.rect = rect
    decorate(rect: self.rect)
}

func decorate(rect:CGRect) {


    //self.backgroundColor = UIColor.clear 
    //IMPORTANT: dont forgot to set bg color of your view to clear color from story board's property inspector 

    let ref = UIGraphicsGetCurrentContext()
    let contentRect = rect.insetBy(dx: 5, dy: 5);
    /*create the rounded oath and fill it*/
    let roundedPath = UIBezierPath(roundedRect: contentRect, cornerRadius: 5)
    ref!.setFillColor("your color for background".cgColor)
    ref!.setShadow(offset: CGSize(width:0,height:0), blur: 5, color: "your color for shado".cgColor)
    roundedPath.fill()

    /*draw a subtle white line at the top of view*/
    roundedPath.addClip()
    ref!.setStrokeColor(UIColor.red.cgColor)
    ref!.setBlendMode(CGBlendMode.overlay)
    ref!.move(to: CGPoint(x:contentRect.minX,y:contentRect.minY+0.5))
    ref!.addLine(to: CGPoint(x:contentRect.maxX,y:contentRect.minY+0.5))
}

}

更新

扩展方法

还有另一种方法.只需创建一个空类并粘贴遵循 UIImageView 扩展代码,将此子类分配给您阴影的那个 ImageView.

There is another Approach. Just Make a class with empty and paste Following UIImageView Extension code, Assign this subclass to that ImageView on which you shadow.

import UIKit

class DGShadowView: UIImageView {

    @IBInspectable var intensity:Float = 0.2{
        didSet{
           setShadow()
        }
    }
    override func layoutSubviews()
    {
        super.layoutSubviews()
        setShadow()
    }

    func setShadow(){
        let shadowPath = UIBezierPath(rect: bounds)
        layer.masksToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize(width: 0.0, height: 0.3)
        layer.shadowOpacity = intensity
        layer.shadowPath = shadowPath.cgPath
    }
}