ios - Cropping image with Swift and put it on center position -
in swift programming , how crop image , put on center afterwards?
this i've got far ... i've crop image want put on center after
imgview.image = origimage var masklayer = cashapelayer() masklayer.frame = imgview.frame masklayer.path = path.cgpath masklayer.fillcolor = uicolor.whitecolor().cgcolor masklayer.backgroundcolor = uicolor.clearcolor().cgcolor imgview.layer.mask = masklayer uigraphicsbeginimagecontext(imgview.bounds.size); imgview.layer.renderincontext(uigraphicsgetcurrentcontext()) var image = uigraphicsgetimagefromcurrentimagecontext() imgview.image = image uigraphicsendimagecontext();
update :
let rect: cgrect = cgrectmake(path.bounds.minx, path.bounds.miny, path.bounds.width, path.bounds.height) // create bitmap image context using rect let imageref: cgimageref = cgimagecreatewithimageinrect(image.cgimage, rect) imgview.bounds = rect imgview.image = uiimage(cgimage: imageref)
i able center getting path.bound , size , change bounds of imageview. :)
to centered position crop, can halve difference of height , width. can assign bounds new width , height after checking orientation of image (which part longer)
func croptobounds(image: uiimage, width: double, height: double) -> uiimage { let contextimage: uiimage = uiimage(cgimage: image.cgimage)! let contextsize: cgsize = contextimage.size var posx: cgfloat = 0.0 var posy: cgfloat = 0.0 var cgwidth: cgfloat = cgfloat(width) var cgheight: cgfloat = cgfloat(height) // see size longer , create center off of if contextsize.width > contextsize.height { posx = ((contextsize.width - contextsize.height) / 2) posy = 0 cgwidth = contextsize.height cgheight = contextsize.height } else { posx = 0 posy = ((contextsize.height - contextsize.width) / 2) cgwidth = contextsize.width cgheight = contextsize.width } let rect: cgrect = cgrectmake(posx, posy, cgwidth, cgheight) // create bitmap image context using rect let imageref: cgimageref = cgimagecreatewithimageinrect(contextimage.cgimage, rect) // create new image based on imageref , rotate original orientation let image: uiimage = uiimage(cgimage: imageref, scale: image.scale, orientation: image.imageorientation)! return image }
i found of info on @ website in case wanted read further.
Comments
Post a Comment