ios - Combine UILabel and UIImage using CGContext -
i'm having trouble combining uilabel
, uiimage
1 single uiimage
.
i have uilabel
can translated, scaled , rotated user on top of uiimage
(view).
when try combine 1 uiimage
using cgcontext, cgcontexttranslatectm , cgcontextrotatectm label not positioned right when rotated. rotation correct, position not. doing wrong?
there several answers on stack overflow discusses aspects of (combine uilabels (with proper origins) uiimage) not take in account rotation factor.
i've attached image can see 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 }
Comments
Post a Comment