移动imageview时如何将imageview保留在UIView中?

How to keep imageview inside UIView when moving imageview?

我在主视图控制器中有一个 UIView,其中包含 1 imageview.i 使用此方法移动的图像视图。

 - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch *aTouch = [touches anyObject];
   if (aTouch.view == self.sub_View) {
    CGPoint location = [aTouch locationInView:self.sub_View];
    CGPoint previousLocation = [aTouch previousLocationInView:self.sub_View];
    self.imageView.frame = CGRectOffset(self.imageView.frame, (location.x - previousLocation.x), (location.y - previousLocation.y));
    }
}

Imageview 移动完美。但是当我移动时,我必须将 imageview 保留在 UIView 中。这段代码的问题是当我移动 imageview 时它也被移到 UIView 之外。我必须将 imageview 保留在 UIView 内,并且只能在 UIView 内移动。 请帮我解决这个问题。如何为imageview设置边界,使其只能在UIView中移动。

a) 您可以将 UIViewclipsToBounds 属性 设置为 YES

b) 您可以使用下面的代码来移动您的 UIImageView

self.imageView.center = CGPointMake(MAX(0.0, MIN(location.x - previousLocation.x, self.sub_View.bounds.size.width)), MAX(0.0, MIN(location.y - previousLocation.y, self.sub_View.bounds.size.height)));

试试下面的代码。

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch *aTouch = [touches anyObject];
   if (aTouch.view == self.sub_View) {
    CGPoint location = [aTouch locationInView:self.sub_View];
    CGPoint previousLocation = [aTouch previousLocationInView:self.sub_View];
    CGRect newFrame = CGRectOffset(self.imageView.frame, (location.x - previousLocation.x), (location.y - previousLocation.y));
    if(newFrame.origin.x < 0)
         newFrame.origin.x = 0;
    if(newFrame.origin.y < 0)
         newFrame.origin.y = 0;
    if(newFrame.origin.x + newFrame.size.width > self.frame.size.width)
         newFrame.origin.x = self.frame.size.width - self.imageView.frame.size.width;
    if(newFrame.origin.y + newFrame.size.height > self.frame.size.height)
         newFrame.origin.y = self.frame.size.height - self.imageView.frame.size.height;

    self.imageView.frame = newFrame;

    }
}