gpt4 book ai didi

iphone - UIImage 检测触摸和拖动

转载 作者:行者123 更新时间:2023-12-03 18:33:26 24 4
gpt4 key购买 nike

这是一个相当常见的问题,我对此有一些答案,而且我已经接近答案了。我有一个按钮,按下时会创建一个图像(代码如下)

(numImages 在加载时设置为零,并用作创建的所有图像的标签编号的计数)

UIImage *tmpImage = [[UIImage imageNamed:[NSString stringWithFormat:@"%i.png", sender.tag]] retain];
UIImageView *myImage = [[UIImageView alloc] initWithImage:tmpImage];

numImages += 1;

myImage.userInteractionEnabled = YES;
myImage.tag = numImages;
myImage.opaque = YES;
[self.view addSubview:myImage];
[myImage release];

然后我有一个 TouchesBegan 方法来检测触摸的内容。我需要它做的是允许用户拖动新创建的图像。它几乎可以工作,但是当您拖动它时,图像会到处闪烁。我可以访问您单击的图像,因为我可以获得它的标签,但我只是无法很好地拖动它。

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

UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];

if (touch.view.tag > 0) {
touch.view.center = location;
}

NSLog(@"tag=%@", [NSString stringWithFormat:@"%i", touch.view.tag]);

}

- (void) touchesMoved:(NSSet *)touches withEvent: (UIEvent *)event {
[self touchesBegan:touches withEvent:event];
}

它的工作原理是,当我单击每个图像时,我会得到每个图像的标签输出。但是当我拖动时,它会闪烁...有什么想法吗?

最佳答案

为了回答我自己的问题 - 我决定创建一个类来处理我放置在 View 上的图像。

如果有人感兴趣,请编写代码......

可拖动.h

#import <Foundation/Foundation.h>
@interface Draggable : UIImageView {
CGPoint startLocation;
}
@end

可拖动.m

#import "Draggable.h"
@implementation Draggable

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
// Retrieve the touch point
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
// Move relative to the original touch point
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

并调用它

UIImage *tmpImage = [[UIImage imageNamed:"test.png"] retain];
UIImageView *imageView = [[UIImageView alloc] initWithImage:tmpImage];

CGRect cellRectangle;
cellRectangle = CGRectMake(0,0,tmpImage.size.width ,tmpImage.size.height );
UIImageView *dragger = [[Draggable alloc] initWithFrame:cellRectangle];
[dragger setImage:tmpImage];
[dragger setUserInteractionEnabled:YES];

[self.view addSubview:dragger];
[imageView release];
[tmpImage release];

关于iphone - UIImage 检测触摸和拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1991899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com