在边界内旋转图像

Rotate image in bounds

我尝试在其超级视图中旋转图像视图,以便该图像视图在旋转时始终接触超级视图的边界而不是越过它们,并适当调整大小。我该如何实施?图片视图应该可以 360˚ 旋转。

这里我使用基于三角形公式的计算,考虑初始图像视图对角线角度。

也许我应该考虑图像视图旋转后的新边界框(它的 x 和 y 坐标变为负数,并且变换后的框架大小也变大)。

到目前为止没有成功,我的图像视图尺寸缩小得太快而且太多了。因此,据我所知,我的目标是为 CGAffineTransformScale 获得适当的比例因子。也许还有其他方法可以做到这一点。

// set initial values

    _planImageView.layer.affineTransform = CGAffineTransformScale(CGAffineTransformIdentity, 1, 1);

    _degrees = 0;

    _initialWidth = _planImageView.frame.size.width;
    _initialHeight = _planImageView.frame.size.height;
    _initialAngle = MathUtils::radiansToDegrees(atan((_initialWidth / 2) / (_initialHeight / 2)));

// rotation routine

- (void)rotatePlanWithDegrees:(double)degrees
{
    double deltaDegrees = degrees - _degrees;
    _initialAngle -= deltaDegrees;
    double newAngle = _initialAngle;
    double newWidth = (_initialWidth / 2) * tan(MathUtils::degreesToRadians(newAngle)) * 2;
    double newHeight = newWidth * (_initialHeight / _initialWidth);

    NSLog(@"DEG %f DELTA %f A %f W %f H %f", degrees, deltaDegrees, newAngle, newWidth, newHeight);

    double currentScale = newWidth / _initialWidth;

    _planImageView.layer.affineTransform = CGAffineTransformScale(CGAffineTransformIdentity, currentScale, currentScale);
    _planImageView.layer.affineTransform = CGAffineTransformRotate(_planImageView.layer.affineTransform, (CGFloat) MathUtils::degreesToRadians(degrees));

    _degrees = degrees;

    self->_planImageView.center = _center;

//    NSLog(@"%@", NSStringFromCGRect(_planImageView.frame));
}

编辑

感谢答案,我重写了例程,现在可以了!

- (void)rotatePlanWithDegrees:(double)degrees
{
    double newWidth =
            _initialWidth  * abs(cos(MathUtils::degreesToRadians(degrees))) +
            _initialHeight * abs(sin(MathUtils::degreesToRadians(degrees)));
    double newHeight =
            _initialWidth  * abs(sin(MathUtils::degreesToRadians(degrees))) +
            _initialHeight * abs(cos(MathUtils::degreesToRadians(degrees)));

    CGFloat scale = (CGFloat) MIN(
            self.planImageScrollView.frame.size.width / newWidth,
            self.planImageScrollView.frame.size.height / newHeight);

    CGAffineTransform rotationTransform = CGAffineTransformMakeRotation((CGFloat) MathUtils::degreesToRadians(degrees));
    CGAffineTransform scaleTransform  = CGAffineTransformMakeScale(scale, scale);
    _planImageView.layer.affineTransform = CGAffineTransformConcat(rotationTransform, scaleTransform);

    self->_planImageView.center = _center;
}

旋转矩形 W x H 时,边界框的尺寸为 W' = W |cos Θ| + H |sin Θ|H' = W |sin Θ| + H |cos Θ|

如果您需要将其放入 W" x H" 矩形中,则比例因子是 W"/W'H"/H' 中最小的一个。