【问题标题】:How to keep imageview inside UIView when moving imageview?移动imageview时如何将imageview保留在UIView中?
【发布时间】:2016-04-19 10:32:18
【问题描述】:

我在主视图控制器中有一个 UIView,其中包含 1 个 imageview。我用这个方法移动了 imageview。

 - (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 之外。我必须将图像视图保留在 UIView 内,并且只能在 UIView 内移动。 请帮我解决这个问题。如何为 imageview 设置边界,使其只能在 UIView 内移动。

【问题讨论】:

  • 什么是self.sub_View
  • 它是主视图上的 UIview,其中包含 imageview

标签: ios objective-c uigesturerecognizer uitouch


【解决方案1】:

试试下面的代码。

- (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;

    }
}

【讨论】:

  • 现在移动在 Uiview 内部,但是当我缩放 imageview 时,它会重置 imagevuew 框架,并且当你滚动时它会隐藏图像..
  • self.frame.size.width 是什么意思?
【解决方案2】:

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)));

【讨论】:

  • 在第一次移动后图像视图保持在左上角。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
  • 2020-05-05
相关资源
最近更新 更多