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

标签 ios swift

我有一个带有圆角半径和阴影的自定义 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/

相关文章:

ios - 我的节目转场不使用 NavigationController

ios - 无法在包 Xcode8 中加载 NIB

ios - 使用 Swift 连接方法修改倒数第二个连接器?

ios - 如何使用 UITextFieldViewModeWhileEditing 检测 UITextField 是否已清除

ios - 如何修改当我完成跳转到其他应用程序时显示的警报 View 的文本

ios - Youtube 视频有时在 ios 中不起作用

ios - 快速解析地理点未获取当前位置

ios - 具有 2 个多行 UILabels/自调整大小 Collection View 单元格的 UICollectionViewCell 高度

IOS 无法在运行时重新定位 UIImageView

swift - Alamofire 照片上传,正文中包含文件 key