Skip to content

Commit

Permalink
Merge pull request #2194 from onevcat/fix/gif-loading-crash
Browse files Browse the repository at this point in the history
Use the unretained version of CGImage to avoid racing
  • Loading branch information
onevcat authored Jan 11, 2024
2 parents ad51380 + fa7ff16 commit e4ab303
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
19 changes: 19 additions & 0 deletions Sources/Image/ImageDrawing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,25 @@ extension CGImage {
}
return decodedImageRef
}

static func create(ref: CGImage) -> CGImage? {
guard let space = ref.colorSpace, let provider = ref.dataProvider else {
return nil
}
return CGImage(
width: ref.width,
height: ref.height,
bitsPerComponent: ref.bitsPerComponent,
bitsPerPixel: ref.bitsPerPixel,
bytesPerRow: ref.bytesPerRow,
space: space,
bitmapInfo: ref.bitmapInfo,
provider: provider,
decode: ref.decode,
shouldInterpolate: ref.shouldInterpolate,
intent: ref.renderingIntent
)
}
}

extension KingfisherWrapper where Base: KFCrossPlatformImage {
Expand Down
12 changes: 5 additions & 7 deletions Sources/Views/AnimatedImageView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -524,13 +524,10 @@ extension AnimatedImageView {
self.maxFrameCount = count
self.maxRepeatCount = repeatCount
self.preloadQueue = preloadQueue

GraphicsContext.begin(size: imageSize, scale: imageScale)
}

deinit {
resetAnimatedFrames()
GraphicsContext.end()
}

/// Gets the image frame of a given index.
Expand Down Expand Up @@ -598,13 +595,12 @@ extension AnimatedImageView {
// To get a workaround, create another image ref and use that to create the final image. This leads to
// some performance loss, but there is little we can do.
// https://github.com/onevcat/Kingfisher/issues/1844
guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage),
let decodedImageRef = cgImage.decoded(on: context, scale: imageScale)
else {
// https://github.com/onevcat/Kingfisher/pulls/2194
guard let unretainedImage = CGImage.create(ref: cgImage) else {
return KFCrossPlatformImage(cgImage: cgImage)
}

return KFCrossPlatformImage(cgImage: decodedImageRef)
return KFCrossPlatformImage(cgImage: unretainedImage)
} else {
let image = KFCrossPlatformImage(cgImage: cgImage)
if backgroundDecode {
Expand Down Expand Up @@ -730,3 +726,5 @@ class SafeArray<Element> {
}
#endif
#endif


0 comments on commit e4ab303

Please sign in to comment.