【问题标题】:Why App is crashinhg sometime when create image?为什么应用程序在创建图像时有时会崩溃?
【发布时间】:2021-01-29 12:13:24
【问题描述】:

当我创建 UIView 的图像时,它有时会崩溃。请检查下面是我的代码。而且我无法重新创建它。

 UIGraphicsBeginImageContextWithOptions(BillView.frame.size, BillView.isOpaque, 0.0)
 BillView.layer.render(in: UIGraphicsGetCurrentContext()!) 
 let imgBill = UIGraphicsGetImageFromCurrentImageContext()! // Crash here
 UIGraphicsEndImageContext()

以下是我的崩溃分析。

崩溃:com.apple.main-thread EXC_BREAKPOINT 0x0000000104f49098

0 Figment POS TransactionController.swift - 第 3654 行 TransactionController.createBillImage() + 3654

1 Figment POS - 第 4342993120 行 @objc TransactionController.createBillImage() + 4342993120

2 基金会 __NSFireDelayedPerform + 412

3 核心基础 CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION + 28

4 核心基础 __CFRunLoopDoTimer + 880

5 核心基础 __CFRunLoopDoTimers + 276

6 核心基础 __CFRunLoopRun + 1640

7 CoreFoundation CFRunLoopRunSpecific + 424

8 图形服务 GSEventRunModal + 160

9 UIKitCore UIApplicationMain + 1932

10 Figment POS AppDelegate.swift - 第 39 行 main + 39

11 libdyld.dylib 开始 + 4

【问题讨论】:

  • 不要强制解开 UIGraphicsGetImageFromCurrentImageContext 的结果 - 更优雅地处理 nil。那么你的问题就变成了为什么这个函数有时会返回nil

标签: ios swift xcode


【解决方案1】:

要安全地展开可选值,您可以使用if-letguard-let

例如。

guard let context = UIGraphicsGetCurrentContext() else {
   print("graphic context is not available so you can not create an image.")
   return
}

UIGraphicsBeginImageContextWithOptions(BillView.frame.size, BillView.isOpaque, 0.0)
BillView.layer.render(in: context) 
if let imgBill = UIGraphicsGetImageFromCurrentImageContext() {
  //here you will get image for sure 
  print(imgBill.size)
} else {
  //this is the case when image is nil
}
UIGraphicsEndImageContext()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 2011-04-17
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多