gpt4 book ai didi

objective-c - 将 uiimage 拖放到另一个 uiimageview 中

转载 作者:太空狗 更新时间:2023-10-30 03:51:13 26 4
gpt4 key购买 nike

我正在使用以下代码片段来拖放 uiimageview

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[myImageView addGestureRecognizer:panRecognizer];

-(void)move:(id)sender {

CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];

if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {

firstX = [myImageView center].x;
firstY = [myImageView center].y;
}

translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[myImageView setCenter:translatedPoint];

}

这段代码是拖动整个 myImageView ,但我的要求是只拖动 uiimage 并将它放到另一个 uiimagview 中。myImageView 应该在拖动后保持原样。只是我需要拖动 myImageView 层。可拖动图像应该是透明的。任何想法将不胜感激。

最佳答案

我付出了很少的努力来实现你的输出。试试吧

第 1 步:在您的 .h 文件中定义这 3 个变量

UIImageView *ivSource1, *ivDestination2, *tempIV;

第 2 步:初始化所有三个 UIImageView 并将其添加到您的 ViewController 中,将其写入 viewDidLoad 方法

ivSource1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.jpg"]];
[ivSource1 setFrame:CGRectMake(100, 100, 100, 100)];
[ivSource1 setTag:100];
[ivSource1 setUserInteractionEnabled:YES];
[self.view addSubview:ivSource1];

ivDestination2 = [[UIImageView alloc] init];
[ivDestination2 setFrame:CGRectMake(200, 300, 100, 100)];
[ivDestination2 setTag:101];
[ivDestination2 setUserInteractionEnabled:YES];
[self.view addSubview:ivDestination2];

tempIV = [[UIImageView alloc] init];
[tempIV setFrame:CGRectMake(0, 300, 100, 100)];
[tempIV setTag:102];
[tempIV setUserInteractionEnabled:YES];
[self.view addSubview:tempIV];

第 3 步:定义以下触摸方法来处理拖放图像的移动

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];

if([[touch view] tag] == 100)
{
[tempIV setImage:ivSource1.image];
[tempIV setCenter:[touch locationInView:self.view]];
}
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];

[tempIV setCenter:[touch locationInView:self.view]];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
[tempIV setCenter:[touch locationInView:self.view]];

if(CGRectContainsPoint(ivDestination2.frame, [touch locationInView:self.view]))
{
[ivDestination2 setImage:tempIV.image];
}
// Remove image from dragable view
[tempIV setImage:[UIImage imageNamed:@""]];
}

关于objective-c - 将 uiimage 拖放到另一个 uiimageview 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16564251/

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