2017年12月25日 星期一

利用CGContext轉出bitmap點陣字

import Foundation
import Cocoa
func text2bitmap(text: String, font: NSFont) -> [[Bool]]? {
let attributes = [NSAttributedStringKey.font:font]
let size = text.size(withAttributes: attributes)
let width = Int(size.width)
let height = Int(size.height)
let bytesPerRow = width
let dataSize = bytesPerRow * height
var pixelData = [UInt8](repeating: 0, count: dataSize)
let colorSpace = CGColorSpaceCreateDeviceGray()
guard let context = CGContext(data: &pixelData,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)
else {
return nil
}
context.setShouldAntialias(false)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
text.draw(at: NSPoint.zero, withAttributes: attributes)
NSGraphicsContext.restoreGraphicsState()
var isTop = true
var bitmap = [[Bool]]()
for i in 0..<height {
var line = [Bool]()
for j in 0..<width {
let pix = pixelData[i * bytesPerRow + j]
line.append(pix > 128)
}
if isTop {
if line.contains(true) {
isTop = false
bitmap.append(line)
}
} else {
bitmap.append(line)
}
}
while let last = bitmap.last, last.contains(true) == false {
bitmap.removeLast()
}
return bitmap
}
let text = "1"
if
let font = NSFont(name: "Helvetica", size: 8),
let bitmap = text2bitmap(text: text, font: font)
{
for line in bitmap {
var txt = ""
for pix in line {
txt += pix ? "■" : "□"
}
print(txt)
}
}

沒有留言: