UIGraphicsImageRenderer创建的图像具有不同的大小

时间:2019-03-04 11:13:10

标签: core-image cgimage

我创建了一个具有大小的UIGraphicsImageRenderer,但是我得到了一个具有不同大小的cgImage?

enter image description here

让字符串= NSAttributedString(             字符串:“ 0”,             属性:attributeDict)         让大小= string.size()         打印(尺寸)         让traitCollection = UITraitCollection(displayScale:1.0)         让rendererFormat = UIGraphicsImageRendererFormat(for:traitCollection)

    let renderer = UIGraphicsImageRenderer(bounds: CGRect(origin: .zero, size: size), format: rendererFormat)
    let im = renderer.image{ (context) in
        UIColor.black.setStroke()
        let element = CGFloat(grayShade)/CGFloat(255)
        let color = UIColor(red: element, green: element, blue: element, alpha: 1)
        print(color)
        color.setFill()
        context.stroke(renderer.format.bounds)
        context.fill(renderer.format.bounds)
        let rect = context.format.bounds
        print(rect)
        string.draw(in: rect)
    }

    let cg = im.cgImage
    return cg!

1 个答案:

答案 0 :(得分:1)

UIGraphicsImageRenderer有一个与之相关的比例,该比例决定了您创建的尺寸(以磅为单位)如何转换为实际像素。默认情况下,此比例与主显示屏相同。

您可以通过使用其他格式初始化渲染器来更改比例:

let traitCollection = UITraitCollection(displayScale: 1.0)
let rendererFormat = UIGraphicsImageRendererFormat(for: traitCollection)
let renderer = UIGraphicsImageRenderer(bounds: CGRect(origin: .zero, size: size), format: rendererFormat)