我想用圆角同时给一个imageView阴影,但我失败了。
答案 0 :(得分:3)
这是我的解决方案
基本理念:
内部想法: 这里我们在Aview上几乎在边框上使用Bezier路径,并将所有圆角属性和阴影属性设置为该路径,我们将放置目标图像视图谎言在该路径中绑定
@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
}
}
答案 1 :(得分:0)
解决方案是创建两个单独的视图。一个用于阴影,一个用于图像本身。在imageView上你clipToBounds图层,以便正确添加角半径。
将imageView放在shadowView的顶部,你就得到了解决方案!