Draw text background

This commit is contained in:
Simon 2018-12-27 16:12:18 +08:00
parent fc8ecca3fb
commit 2c42405674
5 changed files with 43 additions and 12 deletions

View File

@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "background.jpg",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 MiB

View File

@ -11,13 +11,16 @@ import PlaceholderKit
class ViewController: UIViewController {
var sampleImagesCollectionViewController: SampleImagesCollectionViewController?
let placeholders: [Placeholder] = [
Placeholder(size: CGSize(width: 100, height: 100), backgroundStyle: .solidColor(.red)),
Placeholder(size: CGSize(width: 200, height: 100), backgroundStyle: .solidColor(.blue)),
Placeholder(size: CGSize(width: 100, height: 200), backgroundStyle: .solidColor(.green)),
Placeholder(size: CGSize(width: 320, height: 480), backgroundStyle: .solidColor(.yellow)),
Placeholder(size: CGSize(width: 320, height: 480), backgroundStyle: .image(UIImage(named: "background")!))
]
lazy var images: [UIImage] = {
return [
Placeholder(size: CGSize(width: 100, height: 100), backgroundStyle: .solidColor(.red)),
Placeholder(size: CGSize(width: 200, height: 100), backgroundStyle: .solidColor(.blue)),
Placeholder(size: CGSize(width: 100, height: 200), backgroundStyle: .solidColor(.green)),
Placeholder(size: CGSize(width: 320, height: 480), backgroundStyle: .solidColor(.yellow)),
].compactMap({$0.render()})
return placeholders.compactMap({$0.render()})
}()
override func viewDidLoad() {

View File

@ -32,7 +32,10 @@ public struct Placeholder {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedString.Key.font: Font(name: "HelveticaNeue", size: 20)!, NSAttributedString.Key.paragraphStyle: paragraphStyle]
let attrs = [
NSAttributedString.Key.font: Font(name: "HelveticaNeue", size: 20)!,
NSAttributedString.Key.paragraphStyle: paragraphStyle
]
return attrs
}
@ -45,10 +48,10 @@ public struct Placeholder {
let attributedString = NSAttributedString(string: displayedText,
attributes: displayedTextAttributes)
let textSize = attributedString.size()
let rect = CGRect(x: 0,
let rect = CGRect(x: (size.width - textSize.width) / 2,
y: (size.height - textSize.height) / 2,
width: size.width,
height: size.height)
width: textSize.width,
height: textSize.height)
return rect
}

View File

@ -20,10 +20,14 @@ extension Placeholder {
case .solidColor(let color):
color.setFill()
context.fill(rect)
default:
break
case .image(let image):
image.draw(in: rect)
}
// draw text background
UIColor.white.setFill()
context.fill(textRect.insetBy(dx: -10, dy: 0))
// draw text
displayedText.draw(with: textRect,
options: .usesLineFragmentOrigin,