简体   繁体   English

CGContext fill(_ rect: CGRect) 无法匹配预期结果

[英]CGContext fill(_ rect: CGRect) can not match the expected result

I am new in quartz 2d,I just created a 400 * 300 bitmap image context, and then fill a rect with 200 * 200,but I got a rectangle image rather than square, can anyone explain it?我是石英 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
    }

绘图图像

well,the image is being streched when drawing,if I want to get the prospective answer,I need to set funtion draw(_ image: UIImage, in rect: CGRect, by Tiling: Bool = false) parameter rect size same as the image,or change contentMode the image showing like imageView ,however I don't know how to set in Quartz 2D yet.好吧,绘图时图像被拉伸,如果我想得到预期的答案,我需要设置函数draw(_ image: UIImage, in rect: CGRect, by Tiling: Bool = false)参数rect大小与图像相同,或更改contentMode图像显示为imageView ,但我不知道如何在 Quartz 2D 中设置。 then I change code and finnaly got what I expected.然后我更改了代码,最终达到了我的预期。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM