Last active
August 29, 2015 14:17
-
-
Save Mazyod/b3ba620852500a612a3e to your computer and use it in GitHub Desktop.
Cross platform shapes images using CGImage. Elegantly created using swift and swifty conventions. See more at https://github.com/Mazyod/MazKit
This file contains 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
// | |
// CGImage+Shapes.swift | |
// MazKit | |
// | |
// Created by Mazyad Alabduljaleel on 3/22/15. | |
// Copyright (c) 2015 ArabianDevs. All rights reserved. | |
// | |
import CoreGraphics | |
public extension CGImage { | |
public enum Shape { | |
case Circle(radius: CGFloat) | |
case Rect(width: CGFloat, height: CGFloat) | |
public var size: CGSize { | |
switch self { | |
case .Circle(let radius): | |
return CGSize(width: radius, height: radius) | |
case .Rect(let width, let height): | |
return CGSize(width: width, height: height) | |
} | |
} | |
public var rect: CGRect { | |
return CGRect(origin: CGPoint.zeroPoint, size: size) | |
} | |
public var path: CGPathRef { | |
var bezier: UIBezierPath | |
switch self { | |
case .Circle(let radius): | |
bezier = UIBezierPath(ovalInRect: rect) | |
case .Rect(let width, let height): | |
bezier = UIBezierPath(rect: rect) | |
} | |
return bezier.CGPath | |
} | |
} | |
public class func render(shape: Shape, color: CGColorRef) -> CGImage { | |
let width = UInt(ceil(shape.size.width)) | |
let height = UInt(ceil(shape.size.height)) | |
let bitsPerComponent = 8 as UInt | |
let componentsCount = 4 as UInt | |
let bytesPerPixel = (bitsPerComponent * componentsCount) / 8 | |
let totalBytes = bytesPerPixel * width * height | |
let bytesPerRow = UInt(bytesPerPixel) * width | |
let buffer: UnsafeMutablePointer<Void> = UnsafeMutablePointer.alloc(Int(totalBytes)) | |
memset(buffer, 0, totalBytes) | |
let colorspace = CGColorSpaceCreateDeviceRGB() | |
let bitmapInfo = CGBitmapInfo(CGBitmapInfo.ByteOrder32Big.rawValue + CGImageAlphaInfo.PremultipliedLast.rawValue) | |
let context = CGBitmapContextCreate(buffer, width, height, bitsPerComponent, bytesPerRow, colorspace, bitmapInfo) | |
CGContextSetFillColorWithColor(context, color) | |
CGContextAddPath(context, shape.path) | |
CGContextFillPath(context) | |
return CGBitmapContextCreateImage(context) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment