swift - How to make text appear in centre of the image? -
i want add text on image, , i'm able shown in below code.
func texttoimage(drawtext: nsstring, inimage: uiimage, atpoint:cgpoint)->uiimage{ // setup font specific variables var textcolor: uicolor = uicolor.redcolor() var textfont: uifont = uifont(name: "americantypewriter", size: 75)! let textstyle = nstexteffectletterpressstyle //setup image context using passed image. uigraphicsbeginimagecontext(inimage.size) let textfontattributes = [ nsfontattributename: textfont, nsforegroundcolorattributename: textcolor, nstexteffectattributename : textstyle ] inimage.drawinrect(cgrectmake(0, 0, inimage.size.width, inimage.size.height)) var rect: cgrect = cgrectmake(atpoint.x, atpoint.y, inimage.size.width, inimage.size.height) drawtext.drawinrect(rect, withattributes: textfontattributes) var newimage: uiimage = uigraphicsgetimagefromcurrentimagecontext() uigraphicsendimagecontext() return newimage } i called function shown below
let newimage : uiimage = texttoimage(texttoadd!, inimage: imagetosave, atpoint:cgpoint(x: 20, y: 20)) //for text displaying @ top in left end point(x:20 ,y:20) but problem is, text taken user. can give either single word or big sentence. if give single word, should appear in top , middle of image or else in top left right. more like, want set text alignment centre. achieve it, accordingly should change cgpoint given above. i'm not getting how change should in scenarios. please me how achieve this.
you can center text near top of image this:
func texttoimage(drawtext: nsstring, inimage: uiimage, atpoint:cgpoint)->uiimage{ // setup font specific variables var textcolor: uicolor = uicolor.redcolor() var textfont: uifont = uifont(name: "americantypewriter", size: 75)! let textstyle = nstexteffectletterpressstyle //setup image context using passed image. uigraphicsbeginimagecontext(inimage.size) let textfontattributes = [ nsfontattributename: textfont, nsforegroundcolorattributename: textcolor, nstexteffectattributename : textstyle ] inimage.drawinrect(cgrectmake(0, 0, inimage.size.width, inimage.size.height)) let textsize = drawtext.sizewithattributes(textfontattributes) let textrect = cgrectmake(inimage.size.width / 2 - textsize.width / 2, 0, inimage.size.width / 2 + textsize.width / 2, inimage.size.height - textsize.height) drawtext.drawinrect(textrect, withattributes: textfontattributes) var newimage: uiimage = uigraphicsgetimagefromcurrentimagecontext() uigraphicsendimagecontext() return newimage }
Comments
Post a Comment