使用Swift中的CoreGraphics在屏幕上绘制像素

时间:2016-01-25 07:45:06

标签: swift core-graphics

下面的代码试图将像素设置为离线位图并将位图绘制到屏幕上。不幸的是,它崩溃了。

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)
    }

}

1 个答案:

答案 0 :(得分:4)

需要进行一些更改。 1.由于存在内存溢出而崩溃。 2.您正在从新创建的上下文创建图像并写入相同的上下文而不是当前的绘图上下文。

使用此修改后的drawRect函数:

import numpy as np
def whosMy(*args):
  sequentialTypes = [dict, list, tuple] 
  for var in args:
    t=type(var)
    if t== np.ndarray:  
      print type(var),var.dtype, var.shape
    elif t in sequentialTypes: 
      print type(var), len(var)
    else:
      print type(var)