ios - swift : How to create a UIView with transparent circle in the middle?

标签 ios swift uiview drawrect alpha-transparency

objective-c 有一些答案,但没有找到任何关于 swift 的答案。

我想创建一个中间带有透明圆圈的深色 View ,以便用户可以看到 subview 并与之交互。我如何使用 swift 实现它。

更准确地说,我正在寻找类似 whatsapp 个人资料图片实现的结果。中间有一个透明圆圈,用户可以看到图片并滚动。

谢谢大家的帮助!

最佳答案

Cyril 的回答被翻译成 swift 以防止额外打字:

    func circularOverlayMask() -> UIImage {
        let bounds = self.view.bounds
        let width = bounds.size.width
        let height = bounds.size.height
        let diameter = width
        let radius = diameter / 2
        let center = CGPointMake(width / 2, height / 2)

        // Create the image context
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)

        // Create the bezier paths
        let clipPath = UIBezierPath(rect: bounds)
        let maskPath = UIBezierPath(ovalInRect: CGRectMake(center.x - radius, center.y - radius, diameter, diameter))

        clipPath.appendPath(maskPath)
        clipPath.usesEvenOddFillRule = true

        clipPath.addClip()
        UIColor(white: 0, alpha: 0.5).setFill()
        clipPath.fill()

        let finalImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()

        return finalImage
    }

关于ios - swift : How to create a UIView with transparent circle in the middle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28723120/

相关文章:

objective-c - UITableView 被 UITabBar 部分隐藏

php - 如何使用 CloudKit Web 服务创建 CKReference?

ios - 如何从坐标中提取用户的城市

uiview - 在 Swift 中创建一个对角自定义 UIView

ios - Swift drawRect 函数不会更新绘图

ios - UITableView 中每个 UITableViewcell 的 SwitchView

iOS swift : Using delegate methods in custom class

ios - 使用 Swift 3 进行 JSON 解析

ios - 更改 NSLayoutConstraint 的常量

ios - 分段控制 - 发送到实例的无法识别的选择器