Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing pixels on the screen using CoreGraphics in Swift

The code below is trying to set pixels to an offline bitmap and draw the bitmap to the screen. Unfortunately, it crashes.

import UIKit

class GameView: UIView {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }


    func createBitmapContext(pixelsWide: Int, _ pixelsHigh: Int) -> CGContextRef? {
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * pixelsWide
        let bitsPerComponent = 8

        let byteCount = (bytesPerRow * pixelsHigh)

        let colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB)

        let pixels = UnsafeMutablePointer<CUnsignedChar>.alloc(byteCount)
        if pixels == nil {
            return nil
        }
        let bitmapInfo = CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue

        let context = CGBitmapContextCreate(pixels, pixelsWide, pixelsHigh, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)

        return context
    }

    override func drawRect(rect: CGRect) {
        let width  = 200
        let height = 300
        let boundingBox = CGRectMake(0, 0, CGFloat(width), CGFloat(height))
        let context = createBitmapContext(width, height)

        let data = CGBitmapContextGetData(context)
        var currentPixel: [UInt32] = unsafeBitCast(data, [UInt32].self)

        var n = 0
        for var j = 0; j < height; j++ {
            for var i = 0; i < width; i++ {
                currentPixel[n++] = 0
            }
        }

        let image = CGBitmapContextCreateImage(context!)
        CGContextDrawImage(context!, boundingBox, image)
    }

}
like image 586
John Difool Avatar asked Jan 25 '16 07:01

John Difool


People also ask

What is Core Graphics in Swift?

You use this framework to handle path-based drawing, transformations, color management, offscreen rendering, patterns, gradients and shadings, image data management, image creation, and image masking, as well as PDF document creation, display, and parsing.

How does Core Graphics work?

Core Graphics uses what's called a “painter's model”. When you draw into a context, it's almost like making a painting. You lay down a path and fill it, and then lay down another path on top and fill it. You can't change the pixels that have been laid down, but you can paint over them.


1 Answers

There are couple changes required. 1. Crashing because of there was memory overrun. 2. You are creating image from newly created context and writing to same context instead of current drawing context.

Use this modified drawRect Function:

override func drawRect(rect: CGRect) {
    let width  = 200
    let height = 300
    let boundingBox = CGRectMake(0, 0, CGFloat(width), CGFloat(height))
    let context = createBitmapContext(width, height)

    let data = CGBitmapContextGetData(context)

    let pixels = UnsafeMutablePointer<CUnsignedChar>(data)
    var n = 0
    for var j = 0; j < height; j++ {
        for var i = 0; i < width; i++ {
            pixels[n++] = 0 //B
            pixels[n++] = 255 //G
            pixels[n++] = 0 //R
            pixels[n++] = 255 //A
        }
    }
    let image = CGBitmapContextCreateImage(context!)
    if let currentContext: CGContext! = UIGraphicsGetCurrentContext() {
        UIImagePNGRepresentation(UIImage(CGImage:image!))?.writeToFile("/Users/admin/Desktop/aaaaa.png", atomically: true)
        CGContextDrawImage(currentContext, boundingBox, image)
    }
}
like image 145
Arun Ammannaya Avatar answered Nov 26 '22 19:11

Arun Ammannaya