Copy some of the scaled UIImage

I want to be able to scale and position the image, and then save only part of this image. I currently have a UIImageView inside a UIScrollView. After zooming and positioning the image, I press the button, and then enter the following code.

// imageScale = current scale of UIView
// get the new width and height of the scaled UIView
float scaledImageWidth = [scrollView viewWithTag:1].frame.size.width;
float scaledImageHeight = [scrollView viewWithTag:1].frame.size.height;

// get starting X and Y coords of target in relation to UIView 
// target is a box in the middle of the screen, 210x255px
float imageY = scaledImageHeight / 2 - (scrollView.contentOffset.y * imageScale);
imageY = (imageY < 0) ? (140 * imageScale) + ((imageY * -1) + (scrollView.contentOffset.y *imageScale)) : (140 * imageScale) - imageY;

float imageX = scaledImageWidth / 2 - (scrollView.contentOffset.x * imageScale);
imageX = (imageX < 0) ? (56 * imageScale) + ((imageX * -1) + (scrollView.contentOffset.x *imageScale)) : (56 * imageScale) - imageX;

// image = original unscaled UIImage
// create new UIImage that matches the size of the scaled UIView we have been working with
UIGraphicsBeginImageContext( CGSizeMake(scaledImageWidth, scaledImageHeight) );
[image drawInRect:CGRectMake(0,0,scaledImageWidth, scaledImageHeight)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// now with the UIImage that is the size we want, copy a piece of the image 
CGImageRef imageRef = CGImageCreateWithImageInRect([newImage CGImage], CGRectMake(imageX,imageY,210, 255));
UIImage* myThumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

This seems to work mostly fine. The problem that I see is that when I make the final copy of only part of the image, the copy (myThumbnail) does not scale. However, the source (newImage) seems to scale without problems. Does anyone know what I am missing, or if there will be a different approach to this problem?

Edit: , . . , , , . , , . , , , , .

+3

Source: https://habr.com/ru/post/1728535/


All Articles