gpt4 book ai didi

ios - Swift - 将图像添加到圆形 View

转载 作者:搜寻专家 更新时间:2023-11-01 06:03:58 56 4
gpt4 key购买 nike

我有一个带有圆角半径和阴影的自定义 View ,我想在其中添加一个图像。图像应该在圆形区域内。但是我在 View 中看到了一个黑色区域,图像应该在那里(或者在我最后一次尝试时图像是一个没有圆角的正方形)。如何添加此图片?

我得到的错误结果:

enter image description here

我的代码:

import Foundation
import UIKit

@IBDesignable

class RoundedSquareView: UIView {
var shadowLayer: CAShapeLayer!
@IBInspectable var image: UIImage! = UIImage()

override func layoutSubviews() {
super.layoutSubviews()

if shadowLayer == nil {
shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 14).cgPath
shadowLayer.fillColor = UIColor.white.cgColor

shadowLayer.shadowColor = UIColor.darkGray.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 0, height: 10.0)
shadowLayer.shadowOpacity = 0.3
shadowLayer.shadowRadius = 10

layer.insertSublayer(shadowLayer, at: 0)
}

let imgLayer = CAShapeLayer()
let myImage = image.cgImage
imgLayer.frame = bounds
imgLayer.masksToBounds = true
imgLayer.contents = myImage
imgLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 14).cgPath
imgLayer.cornerRadius = 14
layer.addSublayer(imgLayer)
}

}

编辑:

预期结果:

enter image description here

最佳答案

您可以尝试一个简单的扩展。这是一个例子:

extension UIImageView {
func render(with radius: CGFloat) {

// add the shadow to the base view
self.backgroundColor = UIColor.clear
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 10)
self.layer.shadowOpacity = 0.3
self.layer.shadowRadius = 10

// add a border view for corners
let borderView = UIView()
borderView.frame = self.bounds
borderView.layer.cornerRadius = radius
borderView.layer.masksToBounds = true
self.addSubview(borderView)

// add the image for clipping
let subImageView = UIImageView()
subImageView.image = self.image
subImageView.frame = borderView.bounds
borderView.addSubview(subImageView)

//for performance
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 10).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
}
}

用法:

myImageView.image = image
myImageView.render(with: 10)

显然,您可以向扩展添加任意数量的参数、设置默认值、将其分解为单独的方法等。

结果:

enter image description here

关于ios - Swift - 将图像添加到圆形 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42281445/

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