【问题标题】:Change UIImageView size and move it with touch gesture更改 UIImageView 大小并使用触摸手势移动它
【发布时间】:2012-09-12 10:49:43
【问题描述】:

在我的应用程序中,我有一个用户可以触摸和移动的 UIImageView。 当触摸开始改变图像的大小时,我需要它。 为此我实现了这个方法

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

并在其中更改大小,然后使用 UIPanGestureRecognizer 移动图像。

唯一的问题是,当触摸开始时,尺寸会发生变化,但当图像移动时,它会调整为原始尺寸。 感谢您的帮助!

【问题讨论】:

  • 您到底需要什么?触摸时它的大小会改变并且可以移动?
  • UIPanGestureRecognizer 将吞下 touchesBegan/Ended 事件,除非 cancelsTouchesInView 设置为 NO,这听起来像您的代码所期望的那样。
  • 触摸和移动时需要改变它的大小,但在移动开始时大小又变回了移动前的原始大小

标签: iphone ios cocoa-touch uiimageview resize


【解决方案1】:

我建议工作流程应该是:

  1. 在 touchesBegan 中,记录当前图像大小和触摸位置
  2. 在touchesEnded中,比较结束触摸位置的值和touchesBegan记录的触摸位置,以两个位置的比例刷新图像大小。

【讨论】:

  • 此外,如果你想可视化图像的“增长”,你可以实现 touchesMoved。
  • 谢谢,但我想用 PanGesture,因为我有更多的触摸操作
【解决方案2】:

只需使用 touchesMoved 来移动图像。

@interface TTImageView : UIImageView
{
     CGPoint startLocation;
}
@end

@implementation TTImageView

- (id)init
{
    self = [super init];
    if (self) {
        [self setBackgroundColor:[UIColor redColor]];
        [self setUserInteractionEnabled:YES];
        [self setFrame:CGRectMake(0, 0, 100, 100)];
    }
    return self;
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint pt = [[touches anyObject] locationInView:self];
    startLocation = pt;
    [[self superview] bringSubviewToFront:self];

    //change the size of the image
    CGRect frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, 150, 150);
    [self setFrame:frame];
}

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event

{
    CGPoint pt = [[touches anyObject] locationInView:self];
    CGRect frame = [self frame];
    frame.origin.x += pt.x - startLocation.x;
    frame.origin.y += pt.y - startLocation.y;
    [self setFrame:frame];

}
@end

【讨论】:

  • [self setFrame:frame];我没有使用那条线,那是我的错误,现在完美了,谢谢!
  • 我不会继承 UIImageView 只是为了获得这种行为 UIPanGestureRecognizer 可能更合适
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多