让图像出现...如何?
有人可以告诉我如何在用户点击屏幕时显示图像并使其出现在点击的位置吗? 提前致谢, 泰特美术馆
Could someone please tell me how to make an image appear when the user taps the screen and make it appear at the position of the tap.
Thanks in advance,
Tate
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
爱*していゐ2024-09-11 07:32:24
您可以创建一个初始星星,并在每次触摸视图时移动它。
我不确定你的最终结果会是什么样子。
笔记:
此代码将为您提供 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;
}
}
書生途2024-09-11 07:32:24
这个问题似乎暗示您希望用户能够点击屏幕上的任何位置并在他们点击的地方绘制图像?与点击指定位置并使图像出现在那里相反?
如果是这样,您可能必须使用自定义视图。在这种情况下,您需要执行如下操作:
- 创建
UIView
的子类。 - 重写
touchesBegan
方法。调用[[touches anyObject] locationInView:self]
(其中touches
是该方法的第一个参数,是UITouch< 的
NSSet
/code>objects)来获取触摸的位置,并记录下来。 - 重写
touchesEnded
方法。使用与步骤 2 相同的方法确定触摸结束的位置。 - 如果第二个位置靠近第一个位置,则您需要将图像放置在该位置。记录该位置并调用
[self setNeedsDisplay]
来重新绘制自定义视图。 - 重写
drawRect
方法。在这里,如果位置已在步骤 4 中设置,您可以使用UIImage
方法drawAtPoint
在所选位置绘制图像。
有关更多详细信息,此链接可能值得一看。希望有帮助!
编辑:我注意到您之前已经问过基本相同的问题。如果您对那里给出的答案不满意,通常认为“推翻”旧问题更好,也许通过编辑它来要求进一步澄清,而不是创建一个新问题。
编辑:根据要求,下面是一些非常简短的示例代码。这可能不是最好的代码,而且我还没有测试过它,所以它可能有点不确定。澄清一下,THRESHOLD
允许用户在点击时稍微移动手指(最多 3 像素),因为如果手指不移动一点,则很难点击。
MyView.h
#define THRESHOLD 3*3
@interface MyView : UIView
{
CGPoint touchPoint;
CGPoint drawPoint;
UIImage theImage;
}
@end
MyView.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
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
UIView
是UIResponder
,它具有以下可能有帮助的方法:-touchesBegan:withEvent:
,-touchesEnded:withEvent:
、-touchesCancelled:withEvent:
和-touchesMoved:withEvent:
。其中每个参数的第一个参数是
UITouch
对象的NSSet
。UITouch
有一个-locationInView:
实例方法,应生成视图中点击的位置。UIView
is a subclass ofUIResponder
, which has the following methods that might help:-touchesBegan:withEvent:
,-touchesEnded:withEvent:
,-touchesCancelled:withEvent:
and-touchesMoved:withEvent:
.The first parameter of each of those is an
NSSet
ofUITouch
objects.UITouch
has a-locationInView:
instance method which should yield the position of the tap in your view.