I'm having trouble combining a UILabel
and UIImage
to one single UIImage
.
I have a UILabel
that can be translated, scaled and rotated by the user on top of a UIImage
(View).
When i try to combine to one UIImage
using CGContext, CGContextTranslateCTM and CGContextRotateCTM the label is not positioned right when its rotated. The rotation is correct, but the position is not. What am i doing wrong?
There are several answers on Stack overflow that discusses some aspects of this (Combine all UILabels (with proper origins) into a UIImage) but they does not take in account the rotation factor.
I've attached an image where you can see the result.
func bake(image:UIImage, withLabel label: UILabel, outputSize:CGSize) -> UIImage? {
let inputSize:CGSize = image.size
let scale = max(outputSize.width / inputSize.width, outputSize.height / inputSize.height)
let scaledSize = CGSizeMake(inputSize.width * scale, inputSize.height * scale)
let center = CGPointMake(outputSize.width / 2, outputSize.height / 2)
let outputRect = CGRectMake(center.x - scaledSize.width/2, center.y - scaledSize.height/2, scaledSize.width, scaledSize.height)
UIGraphicsBeginImageContextWithOptions(outputSize, true, 0.0)
let context:CGContextRef = UIGraphicsGetCurrentContext()!
CGContextSetInterpolationQuality(context, CGInterpolationQuality.High)
image.drawInRect(outputRect)
if let text = label.text {
if text.characters.count > 0 {
var range:NSRange? = NSMakeRange(0, text.characters.count)
let drawPoint = CGPointMake(
label.frame.origin.x / label.superview!.frame.width * outputSize.width,
label.frame.origin.y / label.superview!.frame.height * outputSize.height)
let originalFont = label.font
label.font = UIFont(name: label.font!.fontName, size: label.font!.pointSize / label.superview!.frame.width * outputSize.width)
let attributes = label.attributedText?.attributesAtIndex(0, effectiveRange: &range!)
let angle = atan2(label.transform.b, label.transform.a)
CGContextTranslateCTM(context, drawPoint.x, drawPoint.y)
CGContextRotateCTM(context, angle)
text.drawInRect(outputRect, withAttributes: attributes)
label.font = originalFont
}
}
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}