如何使用Flutter在iOS和Android上共享图像?
问题描述:
我想在iOS和Android中使用标准共享对话框共享图像。下面的代码大部分来自我用作起点的https://pub.dartlang.org/packages/share(仅Dart和Objective-C在下面)。它目前仅共享文本。如何使用Flutter在iOS和Android上共享图像?
而不是下面的图片我不确定是最好的方法,我将如何将图像转换为Dart中的字节流并在iOS和Android中处理。
飞镖
static const _kShareChannel = const MethodChannel('example.test.com/share');
Future<Null> shareImage(Image image) {
assert(image != null);
return _kShareChannel.invokeMethod('shareImage', image);
}
Objective-C的
static NSString *const PLATFORM_CHANNEL = @"example.test.com/share";
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
FlutterMethodChannel *shareChannel = [FlutterMethodChannel methodChannelWithName:PLATFORM_CHANNEL
binaryMessenger:controller];
[shareChannel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
if ([@"shareImage" isEqualToString:call.method]) {
[self share:call.arguments withController:[UIApplication sharedApplication].keyWindow.rootViewController];
result(nil);
} else {
result([FlutterError errorWithCode:@"UNKNOWN_METHOD"
message:@"Unknown share method called"
details:nil]);
}
}];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
- (void)share:(id)sharedItems withController:(UIViewController *)controller {
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[ sharedItems ]
applicationActivities:nil];
[controller presentViewController:activityViewController animated:YES completion:nil];
}
答
如果图像文件被下载,我会建议将其保存到达特临时文件。
await new File('${systemTempDir.path}/foo.jpg').create();
然后,您可以使用表示图像文件的文件名的URL调用UIActivityViewController
。这里有一些sample code关于如何在非Flutter应用程序中做到这一点,应该让你开始。
如果您的图像文件是动态构建的(例如使用Canvas
API),您可能想知道如何将ui.Image
对象编码为图像文件。 Flutter引擎目前不提供这种方式,可以修改引擎来添加该支持。你可以看看screenshot支持如何实现灵感,但它不会微不足道。