Rotate image using CGContextDrawImage

后端 未结 4 926
既然无缘
既然无缘 2020-12-10 14:00

How can I rotate an image drawn by CGContextDrawImage() at its center?

In drawRect:

CGContextSaveGState(c);

rect = CGRectO         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-10 14:37

    You can use the following method for rotating image.

    -(UIImage*)rotateImage:(UIImage*)img forAngle:(CGFloat)radian   {
    
        UIView *rotatedViewBox = [[UIView alloc]initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
        CGAffineTransform t = CGAffineTransformMakeRotation(radian);
        rotatedViewBox.transform = t;
        CGSize rotatedSize = rotatedViewBox.frame.size;
    
        UIGraphicsBeginImageContext(rotatedSize);
    
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(context, rotatedSize.width, rotatedSize.height);
        CGContextRotateCTM(context, radian);
        CGContextScaleCTM(context, 1.0, -1.0);
    
        CGContextDrawImage(context, CGRectMake(-img.size.width, -img.size.height, img.size.width, img.size.height), img.CGImage);
        UIImage *returnImg = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
        return returnImg;
    }
    

    If you use angle, then here is the macro for converting degree to radian

    #define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
    

提交回复
热议问题