本文介绍了如何在swift3.0.1阴影中同时给一个imageView带圆角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想同时给 imageView 一个带圆角的阴影,但我失败了.
I want to give an imageView a shadow at the same time with rounded corners,but I failed.
推荐答案
这是我的解决方案
基本思路:
- 使用一个额外的视图(比如 AView)作为图像视图的超级视图(对于那些你愿意使用阴影的视图)并将该视图类分配给 DGShadoView
- 将图像视图从左侧、右侧、顶部和底部固定到 AView(即超级视图),常量 5
- 将 AView 的背景颜色设置为 清晰颜色 来自 storybosrd 的属性检查器,这很重要
- 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
- Pin Image view to AView (that super view)from left, right, top and bottom with constant 5
- 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
}
}
这篇关于如何在swift3.0.1阴影中同时给一个imageView带圆角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!