swift - UIScrollView Zooming & contentInset -
simliar ios photos app user zooming in , out of image pinching:
uiview > uiscrollview > uiimageview > uiimage
initially, had issue of zooming below scale 1: image being off centered. got fixed doing this:
func scrollviewdidzoom(scrollview: uiscrollview) { let offsetx = max((scrollview.bounds.width - scrollview.contentsize.width) * 0.5, 0) let offsety = max((scrollview.bounds.height - scrollview.contentsize.height) * 0.5, 0) scrollview.contentinset = uiedgeinsetsmake(offsety, offsetx, 0, 0) }
this works when zooming out.
uiimage content mode aspectfit
issue
when zoom in, when zoomscale above 1, scroll view insets need hug surroundings of uiimage scroll view contains. takes away dead-space surrounding uiimage. ie, photos app when zooming-in pinching or double tapping.
tried
func scrollviewdidzoom(scrollview: uiscrollview) { if scrollview.zoomscale > 1 { let imagescale = (self.imageview.bounds.width/self.imageview.image!.size.width) let imagewidth = self.imageview.image!.size.width * imagescale let imageheight = self.imageview.image!.size.height * imagescale scrollview.contentinset = uiedgeinsetsmake(((scrollview.frame.height - imageheight) * 0.5), (scrollview.frame.width - imagewidth) * 0.5 , 0, 0) print (scrollview.contentinset.top) } else { let offsetx = max((scrollview.bounds.width - scrollview.contentsize.width) * 0.5, 0) let offsety = max((scrollview.bounds.height - scrollview.contentsize.height) * 0.5, 0) scrollview.contentinset = uiedgeinsetsmake(offsety, offsetx, 0, 0) } }
above addition seems vary inset amount still.
update (images added)
first image shows default layout. rest shows when zoomed in.....
your approach looks correct. need update code below.
func scrollviewdidzoom(scrollview: uiscrollview) { if scrollview.zoomscale > 1 { if let image = imageview.image { let ratiow = imageview.frame.width / image.size.width let ratioh = imageview.frame.height / image.size.height let ratio = ratiow < ratioh ? ratiow:ratioh let newwidth = image.size.width*ratio let newheight = image.size.height*ratio let left = 0.5 * (newwidth * scrollview.zoomscale > imageview.frame.width ? (newwidth - imageview.frame.width) : (scrollview.frame.width - scrollview.contentsize.width)) let top = 0.5 * (newheight * scrollview.zoomscale > imageview.frame.height ? (newheight - imageview.frame.height) : (scrollview.frame.height - scrollview.contentsize.height)) scrollview.contentinset = uiedgeinsetsmake(top, left, top, left) } } else { scrollview.contentinset = uiedgeinsetszero } }
Comments
Post a Comment