未处理的 Promise 拒绝:ImageSource.setNativeSource() 需要 UIImage 实例

Unhandled Promise rejection: ImageSource.setNativeSource() expects UIImage instance

使用 Nativescript + Angular,我们正在开发一个允许用户拍照然后将照片上传到服务器的移动应用程序。此应用程序对照片的宽高比有特定要求,因此我们尝试使用 nativescript-bitmap-factory 插件(nativescript-toolbox 的一部分)中的 crop() API 在拍摄照片后裁剪照片。这在 Android 上运行良好但在 iOS 上失败并出现此错误:未处理的承诺拒绝:方法 ImageSource.setNativeSource() 需要 UIImage 实例。这是代码片段:

import * as BitmapFactory from "nativescript-bitmap-factory";

public cropImage(image : ImageSource) : ImageSource {
    let mutable = BitmapFactory.makeMutable(image);
    return BitmapFactory.asBitmap(mutable).dispose((bmp) => {
        let croppedImage = bmp.crop({x:10,y:10}, {width:300,height:300});
       console.log("Image cropped!")
       return croppedImage.toImageSource();
    });
}

最后一行抛出错误

croppedImage.toImageSource();

我检查了 nativescript-bitmap-factory 代码并意识到 crop() API returns 是 CGImage 的一个实例(而不是 ImageSource 期望的 UIImage)。根据这篇文章 https://medium.com/@ranleung/uiimage-vs-ciimage-vs-cgimage-3db9d8b83d94, it is fairly straightforward to convert a CGImage to UIImage in objective-c. I have been struggling for a few days now trying to figure out how to convert a CGImage to UIImage in Nativescript realm. I filed a bug against the nativescript-toolbox (see https://github.com/mkloubert/nativescript-toolbox/issues/10) 几周前,但没有任何回应。 Nativescript 专家能否就如何做到这一点分享一些想法或建议?要求增强 Nativescript ImageSource 以支持 CGImage 是否合理?

您可以使用本地方法将 CGImage 转换为 UIImage

        let mutable = BitmapFactory.makeMutable(image);
        return BitmapFactory.asBitmap(mutable).dispose((bmp) => {
            let croppedImage = bmp.crop({ x: 10, y: 10 }, { width: 300, height: 300 });
            return isAndroid ? croppedImage.toImageSource() :
                fromNativeSource(UIImage.alloc().initWithCGImage(croppedImage.nativeObject));
        });

Playground Sample