UIGraphicsBeginImageContextWithOptions使用及注意事项

本文详细探讨了iOS中UIGraphicsBeginImageContextWithOptions的使用方法,包括参数解析、性能优化建议和常见问题解答,帮助开发者在进行图形绘制时更好地掌控图像上下文的创建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


     /*************************************************************************
     *****************************绘图注意事项**********************************
     *************************************************************************
     *    UIGraphicsBeginImageContextWithOptions函数一定要有对应的
     *    UIGraphicsEndImageContext函数作为结尾,不然会有内存泄漏
     *    这个结尾函数可以多层嵌套:
     *       UIGraphicsBeginImageContextWithOptions(......);
     *       UIGraphicsBeginImageContextWithOptions(......);
     *       UIGraphicsEndImageContext();
     *       UIGraphicsEndImageContext();
     */
    
    UIGraphicsBeginImageContextWithOptions(vImg.frame.size, NO, 1.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
//    CGContextScaleCTM(context, -0.5, 1.0); // 缩放,为负时相当于翻转加缩放(不确定)
//    CGContextTranslateCTM(context, -300, 100); // 偏移
    
    /************************************************************************
    *******************************绘制图片***********************************
    *************************************************************************
    *   会等比例缩放到全图显示,而且会翻转(原因是坐标系不同)
    *    解决方法1:在绘制到context前通过矩阵垂直翻转坐标系
    *        CGContextTranslateCTM(context, 0, height);
    *        CGContextScaleCTM(context, 1.0, -1.0);
    *    解决方法2:使用drawInRect方法(使用这个方法,绘制后和以前图片的宽高比例相同)
    *    解决方法3:颠倒画布
    *        glMatrixMode(GL_PROJECTION);
    *        glLoadIdentity();
    *        glOrthof( 0, framebufferWidth, framebufferHeight, 0, -1, 1 );
    *************************************************************************/
    CGContextTranslateCTM(context, 0, vImg.frame.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, vImg.bounds, img.CGImage); // 绘制图片,也可通过drawInRect方法
    
    UIImage *uiImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值