旋转手势更改视框

时间:2019-09-27 09:03:42

标签: ios objective-c xcode uigesturerecognizer gesture

我想实现的目标:我想创建一个选定视图的副本。 我在UIImageViews上有两个UIView。我同时选择了两个视图,并希望克隆两个视图。

一切正常,直到我不旋转UIImageView为止。如果要旋转视图UIImageView,请更改其框架。

UIView *viewClone = [[UIView alloc]initWithFrame:CGRectMake(fltLeadingMin, fltTopMin, fltCloneViewWidth, fltCloneViewHeight)];
viewClone.backgroundColor = [UIColor redColor];

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
[viewClone addGestureRecognizer:panGesture];

for (UIImageView *imgView in arrSelectedViews) {

    NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:imgView];
    UIImageView *imgViewClone = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];

    imgViewClone.frame = CGRectMake(imgViewClone.frame.origin.x - viewClone.frame.origin.x, imgViewClone.frame.origin.y - viewClone.frame.origin.y, imgView.frame.size.width, imgView.frame.size.height);
    imgViewClone.backgroundColor = UIColor.blueColor;

    [viewClone addSubview:imgViewClone];
}

这是现在的屏幕截图:

enter image description here

1 个答案:

答案 0 :(得分:1)

旋转图像后,其框架将不再起作用,这就是造成问题的原因。

您可以看看Apple document for UIView's transform property

  

如果此属性的值不是恒等变换,则frame属性中的值是未定义的,应忽略。

针对这种情况的解决方案是使用centertransform属性而不是frame

UIView *viewClone = [[UIView alloc]initWithFrame:CGRectMake(fltLeadingMin, fltTopMin, fltCloneViewWidth, fltCloneViewHeight)];
viewClone.backgroundColor = [UIColor redColor];

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
[viewClone addGestureRecognizer:panGesture];

for (UIImageView *imgView in arrSelectedViews) {

    NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:imgView];
    UIImageView *imgViewClone = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];

    // This is the frame before you rotate image, can be replace with another size
    CGRect originalFrame = CGRectMake(0, 0, 200, 200);
    imgViewClone.frame = originalFrame 

    // Using center and transform instead of current frame
    imgViewClone.center = imgView.center;
    imgViewClone.transform = imgView.transform;

    imgViewClone.backgroundColor = UIColor.blueColor;

    [viewClone addSubview:imgViewClone];
}