【问题标题】:CGContext fill(_ rect: CGRect) can not match the expected resultCGContext fill(_rect: CGRect) 无法匹配预期结果
【发布时间】:2020-03-27 09:07:08
【问题描述】:

我是石英 2d 的新手,我刚刚创建了一个 400 * 300 的位图图像上下文,然后用 200 * 200 填充了一个矩形,但我得到的是一个矩形图像而不是正方形,谁能解释一下?

    override func draw(_ rect: CGRect) {
        // Drawing code

        let myBoundingBox = UIScreen.main.bounds
        let myBitmapContext = myCreateBitmapContext(pixelWidth: 400 , pixelHeight: 300 )
        myBitmapContext?.setFillColor(red: 1, green: 0, blue: 0, alpha: 1)
        myBitmapContext?.fill(.init(x: 0, y: 0, width: 200, height: 200))
        guard let myImage = myBitmapContext?.makeImage() else { return }
        let context = UIGraphicsGetCurrentContext()
        context?.draw(myImage, in: myBoundingBox)

    }

    func myCreateBitmapContext(pixelWidth: Int, pixelHeight: Int) -> CGContext? {

        let bytesPerRow = pixelWidth * 4

        guard let colorSpace = CGColorSpace.init(name: CGColorSpace.sRGB) else { return nil }
        let context = CGContext.init(data: nil, width: pixelWidth, height: pixelHeight, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
        return context
    }

【问题讨论】:

  • 听起来 UI 正在通过自动布局等进行拉伸。

标签: ios objective-c swift quartz-2d


【解决方案1】:

嗯,绘图时图片被拉伸,如果我想得到预期的答案,我需要设置功能draw(_ image: UIImage, in rect: CGRect, by Tiling: Bool = false)参数rect与图像相同的大小,或者将contentMode更改为图像显示为@ 987654324@,但是我还不知道如何在 Quartz 2D 中设置。 然后我更改了代码,最终得到了我的预期。

context?.draw(myImage, in: CGRect(x: 0, y: 0, width: 400, height: 300))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    相关资源
    最近更新 更多