iOS - 在 Swift 中的 UIImage 上绘制矩形 (CGRect) 无法正常工作

标签 ios swift uiimage drawrect cgrect

我正在尝试在 UIImage 上绘制矩形(CGRects 数组),这将呈现给最终用户。 最终的结果,由于缺乏更好的短语,看起来很奇怪。例如,如果我有一个包含 2 个 CGRect 的数组,只有一个被绘制,勉强绘制,但不完整。另一个从略。请参阅下图,了解特定 CGRects 数组的图像结果。 (仅供引用:我正在将图像发送到 Google Cloud 进行处理,它以 CGRects 数组响应)

我错过了什么?

private func drawOccurrencesOnImage(_ occurrences: [CGRect], _ image: UIImage) -> UIImage? {
    let imageSize = image.size
    let scale: CGFloat = 0.0
    UIGraphicsBeginImageContextWithOptions(imageSize, false, scale)

    image.draw(at: CGPoint.zero)
    let ctx = UIGraphicsGetCurrentContext()

    ctx?.addRects(occurrences)
    ctx?.setStrokeColor(UIColor.red.cgColor)
    ctx?.setLineWidth(2.0)
    ctx?.strokePath()

    guard let drawnImage = UIGraphicsGetImageFromCurrentImageContext() else {
        presentAlert(alertTitle: "Error", alertText: "There was an issue, please try again")
        return nil
    }

    UIGraphicsEndImageContext()
    return drawnImage
}

值为“[(298.0, 868.0, 65.0, 43.0), (464.0, 1017.0, 67.0, 36.0)]”的 CGRect 数组(上述函数中的“出现次数”)产生下图: Screenshot of UIImage

更多细节:使用 Swift 4、iOS 12

谢谢!

最佳答案

代码是对的。

[(298.0, 868.0, 65.0, 43.0), (464.0, 1017.0, 67.0, 36.0)]”

坐标不对。

请考虑 iPhone 决议。

image


img

imageView.image = drawOccurrencesOnImage([CGRect(x: 100, y: 100, width: 59, height: 60), CGRect(x: 120, y: 50, width: 59, height: 60)], UIImage(named: "person-placeholder")!)

source

关于iOS - 在 Swift 中的 UIImage 上绘制矩形 (CGRect) 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53294522/

相关文章:

ios - 不同形状的图像拼贴

objective-c - objective c singleton dispatch_once 实现更好?

ios - 在应用程序包中添加符号链接(symbolic link)

ios - swift 。选择时更改自定义 Tableview 单元格标签的颜色

ios - Non-Storyboard xib 的容器 View 不显示

ios - 如何在 swift 4 中从 UIImage 读取 exif 数据?

iphone - 为什么这个不同的 "addSubView"代码会导致行为差异

ios - 如何为Realm对象制作通用的GET方法?

ios - YTPlayerView 控件设置不影响全屏模式

objective-c - 从URL提取图像