2016-11-30 108 views

回答

0

解決方案是創建兩個單獨的視圖。一個用於陰影,另一個用於圖像本身。在imageView上clipToBounds圖層,以便正確添加角半徑。

將imageView放在shadowView的頂部,你已經有了解決方案!

3

這裏是我的解決方案

基本思想:

  1. 使用額外的視圖(比如AView)的圖像視圖的超視圖(那些對你願意有shado觀點)和該視圖類分配給DGShadoView
  2. 引腳圖片以AView(即超級視圖)由左,右,頂部和底部具有恆定5
  3. 從storybosrd的屬性檢查器設置回AView的底色清晰的彩色這是很重要的

裏面的想法:這裏我們使用的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。

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 
    } 
}