Pixel-Level Rotation of UIImage Using Core Graphics

Dec 03, 2025 · Programming · 10 views · 7.8

Keywords: UIImage | Core Graphics | Rotation | iOS | Pixel Processing

Abstract: This article explores how to implement 90-degree counterclockwise rotation of UIImage in iOS development through Core Graphics functions, ensuring actual pixel shifting rather than modifying orientation metadata. Based on the best answer, it analyzes the core implementation steps, error avoidance strategies, and supplements with comparisons to other methods for comprehensive technical guidance.

In iOS app development, rotating UIImage is a common image processing requirement, especially when users need to adjust image orientation. Simply modifying the UIImage's orientation property (e.g., UIImageOrientationRight) only changes metadata without moving pixels, which may be insufficient in some scenarios. Thus, this article focuses on a pixel-level rotation method based on Core Graphics, ensuring image data is redrawn.

Problem Background and Core Challenges

A typical issue users face is that when attempting to rotate UIImage, using CGAffineTransform directly may not suit cases requiring pixel shifts. For example, the original question's code tried to achieve rotation via a scaling function but caused a CGBitmapContextCreate error, such as "invalid data bytes/row", indicating improper context parameter setup. This stems from not correctly handling image size and byte row alignment, leading to memory allocation errors.

Implementation of Rotation Function Based on Answer 3

The following code, based on the best answer, provides a simple and efficient rotation function using Core Graphics functions to rotate UIImage by 90 degrees. The function is named rotate, accepts a UIImage source and orientation parameter, and returns the rotated image.

static inline double radians (double degrees) {return degrees * M_PI/180;}
UIImage* rotate(UIImage* src, UIImageOrientation orientation)
{
    UIGraphicsBeginImageContext(src.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orientation == UIImageOrientationRight) {
        CGContextRotateCTM (context, radians(90));
    } else if (orientation == UIImageOrientationLeft) {
        CGContextRotateCTM (context, radians(-90));
    } else if (orientation == UIImageOrientationDown) {
        // No rotation needed
    } else if (orientation == UIImageOrientationUp) {
        CGContextRotateCTM (context, radians(90));
    }

    [src drawAtPoint:CGPointMake(0, 0)];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Code Explanation and Step-by-Step Analysis

The key to this function is using UIGraphicsBeginImageContext to create an image context with the same size as the source image, avoiding the byte row error from the original problem. Rotation is applied via CGContextRotateCTM, with angles converted by the radians function. For instance, 90-degree counterclockwise rotation corresponds to cases like UIImageOrientationUp or UIImageOrientationRight. After rotation, the image is drawn into the context using drawAtPoint, and a new image is generated.

In terms of error avoidance, this method directly uses the source image size as the context dimensions, ensuring proper byte row alignment and preventing CGBitmapContextCreate failures due to parameter mismatches. In contrast, the original code incorrectly used dynamic parameters like CGImageGetBytesPerRow, leading to inconsistent calculations.

Comparison with Other Methods

Referencing other answers, Answer 1 suggests using UIImage's orientation property, such as [[UIImage alloc] initWithCGImage: scale: orientation:]. This approach is simple and thread-safe but only modifies orientation data without changing pixel content, suitable for display adjustments rather than image processing. Answer 2 provides extension methods like imageRotatedByDegrees, based on CGAffineTransform and UIView simulation, which is more comprehensive but code-intensive. The method presented here balances simplicity and pixel-level operation needs, ideal for core rotation scenarios.

Conclusion and Best Practices

For pixel-level rotation of UIImage, the recommended approach is the Core Graphics-based rotate function, which ensures data integrity and avoids common errors. Developers should choose methods based on application needs: use the orientation property for directional adjustments only, or adopt the technique described in this article for actual pixel shifts. Future optimizations may include performance testing or support for arbitrary angle rotations.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.