Update example with different sized output

This commit is contained in:
Simon 2018-12-26 16:38:32 +08:00
parent 57dcb6038d
commit 5b7e8c7c0d
2 changed files with 19 additions and 4 deletions

View File

@ -14,9 +14,9 @@ class ViewController: UIViewController {
lazy var images: [UIImage] = {
return [
PlaceholderBuilder().coloredBackground(color: .red, size: CGSize(width: 100, height: 100)),
PlaceholderBuilder().coloredBackground(color: .blue, size: CGSize(width: 100, height: 100)),
PlaceholderBuilder().coloredBackground(color: .green, size: CGSize(width: 100, height: 100)),
PlaceholderBuilder().coloredBackground(color: .yellow, size: CGSize(width: 100, height: 100)),
PlaceholderBuilder().coloredBackground(color: .blue, size: CGSize(width: 200, height: 100)),
PlaceholderBuilder().coloredBackground(color: .green, size: CGSize(width: 100, height: 200)),
PlaceholderBuilder().coloredBackground(color: .yellow, size: CGSize(width: 320, height: 480)),
].compactMap({$0})
}()

View File

@ -13,12 +13,27 @@ extension UIImage {
static func image(withColor color: UIColor, size: CGSize) -> UIImage? {
let renderer = UIGraphicsImageRenderer(size: size)
let image = renderer.image { context in
let rect = CGRect(origin: .zero, size: size)
// background
color.setFill()
context.fill(CGRect(origin: .zero, size: size))
context.fill(rect)
// text style
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedString.Key.font: UIFont(name: "HelveticaNeue", size: 10)!, NSAttributedString.Key.paragraphStyle: paragraphStyle]
// display string
let string = "\(Int(size.width))x\(Int(size.height))"
// draw text
string.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
}
return image
}
}
#endif