Skip to content

Instantly share code, notes, and snippets.

@rockshassa
Last active March 28, 2019 18:42
Show Gist options
  • Save rockshassa/6fe0bb6ab2f632d0a1f960f91145fe61 to your computer and use it in GitHub Desktop.
Save rockshassa/6fe0bb6ab2f632d0a1f960f91145fe61 to your computer and use it in GitHub Desktop.
image example
import CoreText
import UIKit
class ImageFactory {
class func image(size:CGSize)->CGImage?{
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let ctx = CGContext(data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 8,
bytesPerRow: 8*(Int(size.width)),
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
print("no context")
return nil
}
ctx.setFillColor(UIColor.orange.cgColor)
let fillRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
ctx.fill(fillRect)
ctx.setBlendMode(.clear)
let para = NSMutableParagraphStyle()
para.alignment = .center
let fontSize = floor(size.width*0.8)
let font = UIFont.boldSystemFont(ofSize: fontSize)
// let font = UIFont(name: "GillSans", size: fontSize)!
// let font = UIFont(name: "Kailasa", size: fontSize)!
let attrString = NSAttributedString(string: "L",
attributes: [
.font:font,
.paragraphStyle:para
])
let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)
let stringRange = CFRangeMake(0, attrString.length)
let suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, stringRange, nil, fillRect.size, nil)
let safeSize = CGSize(width: ceil(suggestedSize.width), height: ceil(suggestedSize.height))
print(suggestedSize)
print(safeSize)
let path = CGMutablePath()
path.addRect(CGRect(origin: CGPoint(x: 6, y: 6), size: safeSize))
let frame = CTFramesetterCreateFrame(framesetter, stringRange, path, nil)
print(frame)
let framePath = CTFrameGetPath(frame)
print(framePath)
CTFrameDraw(frame, ctx)
let cgImage = ctx.makeImage()
return cgImage
}
}
let i = ImageFactory.image(size: CGSize(width: 150, height: 150))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment