IOS 开发中相机获取图片 不同方向的相机获取不同的图片的实现 ||图片的从新绘图

来源:互联网 发布:互联网数据分析招聘 编辑:程序博客网 时间:2024/06/05 14:49

http://www.csdn123.com/html/mycsdn20140110/10/1033f42e0a8f810aff2721529c4edcf4.html

这几天在做头像的时候,发现直接拍照获取图片在截取图像的时候不正确,后来发现获取的image 没有设置相机的拍照方向  于是在网上找到了这个方法    


+ (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation

{

    long double rotate = 0.0;

    CGRect rect;

    float translateX = 0;

    float translateY = 0;

    float scaleX = 1.0;

    float scaleY = 1.0;

    

    switch (orientation) {

        case UIImageOrientationLeft:

            rotate = M_PI_2;

            rect = CGRectMake(00, image.size.height, image.size.width);

            translateX = 0;

            translateY = -rect.size.width;

            scaleY = rect.size.width/rect.size.height;

            scaleX = rect.size.height/rect.size.width;

            break;

        case UIImageOrientationRight:

            rotate = 3 * M_PI_2;

            rect = CGRectMake(00, image.size.height, image.size.width);

            translateX = -rect.size.height;

            translateY = 0;

            scaleY = rect.size.width/rect.size.height;

            scaleX = rect.size.height/rect.size.width;

            break;

        case UIImageOrientationDown:

            rotate = M_PI;

            rect = CGRectMake(00, image.size.width, image.size.height);

            translateX = -rect.size.width;

            translateY = -rect.size.height;

            break;

        default:

            rotate = 0.0;

            rect = CGRectMake(00, image.size.width, image.size.height);

            translateX = 0;

            translateY = 0;

            break;

    }

    

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    //CTM变换

    CGContextTranslateCTM(context, 0.0, rect.size.height);

    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextRotateCTM(context, rotate);

    CGContextTranslateCTM(context, translateX, translateY);

    

    CGContextScaleCTM(context, scaleX, scaleY);

    //绘制图片

    CGContextDrawImage(context, CGRectMake(00, rect.size.width, rect.size.height), image.CGImage);

    

    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();

    

    return newPic;

}



发现和我的需求有些不一样  然后研究了一下CTM变换  发现参数改变不一致  于是又修改为



case UIImageOrientationRight:

            rotate = 3 * M_PI_2;

            rect = CGRectMake(0, 0, image.size.width, image.size.height);

            translateX = -rect.size.height;

            translateY = 0;

            scaleY = rect.size.width/rect.size.height;

            scaleX = rect.size.height/rect.size.width;

            break;



只有这一块发生变化    然后复合自己的要求



最后注意  相机在头向右的时候为默认方向   向上的时候为向右偏方向


0 0
原创粉丝点击