触摸时提取图像部分

时间:2017-09-06 21:04:42

标签: ios swift

当用户点击屏幕时,我将图像保存为UIImage。此外,用户触摸坐标也被保存。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first

    if let p = touch?.location(in: view) { }
}

现在,我遇到的问题是我试图放置我从触摸中获得的x和y,并从我最初保存的图像中裁剪一部分。但是,不同的部分会被裁剪。我该如何解决这个问题?

我还找到了this post that says there are issues converting touch points on to a Image.

1 个答案:

答案 0 :(得分:0)

我发布了一个具有相同功能的答案,因为问题非常不清楚仍然可能会有所帮助

这是一个视图层次结构

--> ScrollView 
 --> ViewBase (View might be zoomed and rotated)
   --> TargetImageView (Rect to be cropped (Touch point here for you))

以下是如何做到这一点

CGPoint locationInImageView =  [self.viewBase convertPoint:self.targetImageview.center toView:self.view]; // received from touch
locationInImageView =  [self.view convertPoint:locationInImageView toView:self.imgVPhoto];


UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0);

[self.imgVPhoto.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *img1 = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

// Here  2 is image scale  and zoomScale is what it is zoomed :)

CGFloat width = self.targetImageview.frame.size.width * self.zoomScale / 2 ;
CGFloat height = self.targetImageview.frame.size.height * self.zoomScale  / 2;

CGFloat xPos = (locationInImageView.x  * 2)  - width / 2;
CGFloat yPos = (locationInImageView.y * 2) - height / 2;

CGRect rect1 = CGRectMake(xPos, yPos, width, height);

CGImageRef imageRef = CGImageCreateWithImageInRect([img1 CGImage], rect1);

UIImage *img = [UIImage imageWithCGImage:imageRef scale:img1.scale orientation:img1.imageOrientation];
// Check image here 

希望它对你有所帮助