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

164 views Asked by At

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?

    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
    }

Drawing image

1

There are 1 answers

0
nenseso On

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. then I change code and finnaly got what I expected.

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