Created
December 25, 2017 11:26
-
-
Save yycking/6f1cff64dd5330d6cc01730781365132 to your computer and use it in GitHub Desktop.
String to [[Bool]]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment