ios - Calculate position in image after ScaleAspectFill in UIImageView -


i'm loading images of various sizes inside uiimageview. 1 images come annotations, each annotation has unique position in image. annotation coordinates relative original image size.

how transform coordinates annotation show @ same position in uiimageview after resizing?

i use avmakerectwithaspectratioinsiderect calculate new position, works scaleaspectfit , not scaleaspectfill must use.

you need to:

  • calculate aspectratio aspectfill
  • multiply x,y coords annotation aspectratio
  • adjust point amount of image extends outside view frame

this 1 way (a little verbose, clarity):

func aspectfillpoint(for point: cgpoint, in view: uiimageview) -> cgpoint {      guard let img = view.image else {         return cgpoint.zero     }      // imgsize modified     var imgsize = img.size      let viewsize = view.frame.size      let aspectwidth  = viewsize.width / imgsize.width     let aspectheight = viewsize.height / imgsize.height      // calculate aspectfill ratio     let f = max(aspectwidth, aspectheight)      // scale imgsize     imgsize.width *= f     imgsize.height *= f      // unless aspect ratio of view same image,     // either extend above , below or left , right     // of view frame     let xoffset = (viewsize.width - imgsize.width) / 2.0     let yoffset = (viewsize.height - imgsize.height) / 2.0      // scale original point, , adjust offsets     return cgpoint(         x: (point.x * f) + xoffset,         y: (point.y * f) + yoffset         )  } 

assuming have image assigned theimageview, set .scaleaspectfill, can call this:

let annotationpoint = cgpoint(x: 232, y: 148)  var newpoint = aspectfillpoint(for: annotationpoint, in: theimageview)  // note: newpoint relative view bounds, unless // imageview @ 0,0 need adjust position newpoint.x += theimageview.frame.origin.x newpoint.y += theimageview.frame.origin.y 

Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -