代码之家  ›  专栏  ›  技术社区  ›  ojcar

应用CGAffineTransformRotate后更新帧的原点

  •  1
  • ojcar  · 技术社区  · 11 年前

    我有x和y坐标,以及需要放置在其原始位置上的UIImageView的旋转。旋转后,坐标与视图的坐标相对应。

    我发现的问题是,如果我使用给定的x和y初始化视图,然后执行旋转,则最终位置不正确,因为应用转换的顺序不正确:

    float x, y, w, h; // These values are given 
    
    UIImageView *imageView = [[UIImageView alloc] init];
    
    // Apply transformations
    imageView.frame = CGRectMake(x, y, w, h);
    imageView.transform = CGAffineTransformRotate(imageView.transform, a.rotation);
    

    如果我尝试在旋转视图后使用x和y来平移视图,那么最终的x和y是完全错误的:

    float x, y, w, h; // These values are given 
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(0, 0, w, h);
    
    // Apply transformations
    imageView.transform = CGAffineTransformTranslate(imageView.transform, x, y);
    imageView.transform = CGAffineTransformRotate(imageView.transform, a.rotation);
    

    在应用旋转后,我也尝试更新视图中心,但结果不正确。

    我正在寻找一些关于如何处理这个问题的建议或技巧,以达到我需要的结果。

    提前感谢!

    2 回复  |  直到 11 年前
        1
  •  1
  •   Darius    11 年前

    我使用这个C函数围绕中心进行旋转变换:

    static inline CGAffineTransform CGAffineTransformMakeRotationAroundCenter(double width, double height, double rad) {
        CGAffineTransform t = CGAffineTransformMakeTranslation(height/2, width/2);
        t = CGAffineTransformRotate(t, rad);
        t = CGAffineTransformTranslate(t, -width/2, -height/2);
    
        return t;
    }
    

    您需要以弧度指定宽度、高度和角度。

    这能解决你的问题吗?

        2
  •  1
  •   ojcar    11 年前

    我能够通过计算帧应该位于的原始Y位置和变换视图的原点之间的Y轴偏移来解决这个问题。

    本答案中针对类似问题提供的函数提供了一种方法,通过在所有新角点中创建具有最小X和Y的点来计算帧的新原点:

    -(CGPoint)frameOriginAfterTransform 
    {
        CGPoint newTopLeft = [self newTopLeft];
        CGPoint newTopRight = [self newTopRight];
        CGPoint newBottomLeft = [self newBottomLeft];
        CGPoint newBottomRight = [self newBottomRight];
    
        CGFloat minX = fminf(newTopLeft.x, fminf(newTopRight.x, fminf(newBottomLeft.x, newBottomRight.x)));
        CGFloat minY = fminf(newTopLeft.y, fminf(newTopRight.y, fminf(newBottomLeft.y, newBottomRight.y)));
    
        return CGPointMake(minX, minY);
    }
    

    然后,我计算了Y轴上的偏移,并将其应用于变换视图的中心:

    // Adjust Y after rotating to compensate offset
    CGPoint center = imageView.center;
    CGPoint newOrigin = [imageView frameOriginAfterTransform]; // Frame origin calculated after transform
    CGPoint newCenter = CGPointZero;
    newCenter.x = center.x;
    newCenter.y = center.y + (y - newOrigin.y);
    imageView.center = newCenter;
    

    由于某种原因,偏移仅影响Y轴,尽管起初我认为它会同时影响X轴和Y轴。

    希望这有帮助!