ユーザーが画面をタップしたときに画像を表示し、タップした位置に画像を表示する方法を誰か教えてください。前もってありがとう、テイト
3 に答える
UIView
は のサブクラスでUIResponder
あり、次のメソッドが役立ちます: -touchesBegan:withEvent:
、-touchesEnded:withEvent:
、-touchesCancelled:withEvent:
および-touchesMoved:withEvent:
。
これらのそれぞれの最初のパラメーターは、NSSet
オブジェクトのUITouch
です。UITouch
ビュー内のタップの位置を生成する-locationInView:
インスタンス メソッドがあります。
最初の星を作成し、ビューに触れるたびに移動することができます。最終結果がどのようになるかわかりません。
注: このコードは、タップで移動する 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;
}
}
ユーザーが画面のどこでもタップできるようにして、タップした場所に画像を描画できるようにしたいという質問から暗示されているようです。指定された場所をタップしてそこに画像を表示させるのではなく?
その場合は、おそらくカスタム ビューを使用する必要があります。その場合、次のようなことを行います。
- のサブクラスを作成します
UIView
。 - メソッドをオーバーライドし
touchesBegan
ます。[[touches anyObject] locationInView:self]
(touches
はメソッドの最初の引数NSSet
であるUITouch
オブジェクトの ) を呼び出して、タッチの位置を取得し、記録します。 - メソッドをオーバーライドし
touchesEnded
ます。ステップ 2 と同じ方法を使用して、タッチが終了した位置を特定します。 - 2 番目の場所が最初の場所の近くにある場合は、その場所に画像を配置します。その場所と呼び出しを記録して
[self setNeedsDisplay]
、カスタム ビューを再描画します。 - メソッドをオーバーライドし
drawRect
ます。ここで、手順 4 で場所が設定されている場合は、UIImage
メソッドを使用drawAtPoint
して、選択した場所に画像を描画できます。
詳細については、このリンクを参照してください。それが役立つことを願っています!
編集:以前に本質的に同じ質問をしたことがあることに気づきました。そこにある回答に満足できない場合は、一般的に、新しい質問を作成するよりも、古い質問を編集してさらに明確にするなどして、古い質問を「バンプ」する方がよいと考えられています。
編集:要求に応じて、いくつかの非常に簡単なサンプル コードが続きます。これはおそらく最良のコードではなく、私もテストしていないので、少し不安定かもしれません。明確にするためにTHRESHOLD
、ユーザーはタップ中に指を少し動かすことができます (最大 3px)。これは、指を少し動かさずにタップするのは非常に難しいためです。
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