1

有人可以告诉我如何在用户点击屏幕时显示图像并使其出现在点击位置。在此先感谢,泰特

4

3 回答 3

2

UIView是 的子类UIResponder,它具有以下可能有帮助的方法:-touchesBegan:withEvent:-touchesEnded:withEvent:和。-touchesCancelled:withEvent:-touchesMoved:withEvent:

NSSet每一个的第一个参数是一个UITouch对象。UITouch有一个-locationInView:实例方法,它应该在您的视图中产生水龙头的位置。

于 2010-06-03T23:00:57.490 回答
1

您可以创建一个初始星形,并在每次触摸视图时移动它。我不确定你的最终结果会是什么样子。

注意:此代码将为您提供 1 颗星,点击即可移动这是我的代码:-

(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSSet *allTouches = [event allTouches];
    switch ([allTouches count]) {
        case 1:
        {
            UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
            CGPoint point = [touch locationInView:myView];
            myStar.center = point;  
            break;
        }
        default:
            break;
    }
}
于 2010-07-06T20:05:38.407 回答
0

您希望用户能够点击屏幕上的任何位置并在他们点击的位置绘制图像,这似乎暗示了这个问题?而不是在指定位置点击并让图像出现在那里?

如果是这样,您可能必须使用自定义视图。在这种情况下,您将执行以下操作:

  1. 创建 的子类UIView
  2. 覆盖touchesBegan方法。调用[[touches anyObject] locationInView:self](其中touches是方法的第一个参数,一个NSSet对象UITouch)以获取触摸的位置,并记录它。
  3. 覆盖touchesEnded方法。使用与步骤 2 相同的方法确定位置触摸结束。
  4. 如果第二个位置靠近第一个位置,您需要将图像放置在该位置。记录该位置并调用[self setNeedsDisplay]以重新绘制自定义视图。
  5. 覆盖drawRect方法。在这里,如果位置已在步骤 4 中设置,您可以使用该UIImage方法drawAtPoint在所选位置绘制图像。

有关更多详细信息,此链接可能值得一看。希望有帮助!

编辑:我注意到你以前问过基本相同的问题。如果您对那里给出的答案不满意,通常认为“撞”旧答案更好,也许通过编辑它以要求进一步澄清,而不是创建一个新问题。

编辑:根据要求,下面是一些非常简短的示例代码。这可能不是最好的代码,而且我还没有测试过它,所以它可能有点不确定。只是为了澄清起见,THRESHOLD允许用户在点击时稍微移动手指(最多 3px),因为如果不移动手指就很难点击。

我的视图.h

#define THRESHOLD 3*3

@interface MyView : UIView
{
    CGPoint touchPoint;
    CGPoint drawPoint;
    UIImage theImage;
}

@end

我的视图.m

@implementation MyView

- (id) initWithFrame:(CGRect) newFrame
{
    if (self = [super initWithFrame:newFrame])
    {
        touchPoint = CGPointZero;
        drawPoint = CGPointMake(-1, -1);
        theImage = [[UIImage imageNamed:@"myImage.png"] retain];
    }

    return self;
}

- (void) dealloc
{
    [theImage release];
    [super dealloc];
}

- (void) drawRect:(CGRect) rect
{
    if (drawPoint.x > -1 && drawPoint.y > -1)
        [theImage drawAtPoint:drawPoint];
}

- (void) touchesBegan:(NSSet*) touches withEvent:(UIEvent*) event
{
    touchPoint = [[touches anyObject] locationInView:self];
}

- (void) touchesEnded:(NSSet*) touches withEvent:(UIEvent*) event
{
    CGPoint point = [[touches anyObject] locationInView:self];
    CGFloat dx = point.x - touchPoint.x, dy = point.y - touchPoint.y;

    if (dx + dy < THRESHOLD)
    {
        drawPoint = point;
        [self setNeedsDisplay];
    }
}

@end
于 2010-06-04T00:48:44.930 回答