gpt4 book ai didi

swift - 如何在swift3.0.1阴影中同时给imageView圆角

转载 作者:搜寻专家 更新时间:2023-10-31 22:29:45 24 4
gpt4 key购买 nike

我想同时给一个imageView一个圆角的阴影,但是我失败了。

最佳答案

这是我的解决方案

基本思想:

  1. 使用额外 View (例如 AView)作为 ImageView 的 super View (对于那些您愿意拥有阴影的 View )并将该 View 类分配给 DGShadoView
  2. 将 ImageView 固定到 AView(即 super View ),从左、右、上、下固定 5
  3. AView 的背景颜色设置为 clear color storybosrd 的 Property inspector 这很重要

内部想法: 在这里,我们在 Aview 上几乎在边界处使用贝塞尔路径,并将所有圆角属性和阴影属性设置为该路径,我们将目标 ImageView 放置在在该路径范围内

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

关于swift - 如何在swift3.0.1阴影中同时给imageView圆角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40887532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com