iOS:
- (NSData *)tj_imageNamed:(NSString *)imageName
{
UIImage *image = nil;
if (image == nil) {
image = [UIImage imageNamed:imageName];
if(!image){
image = [[UIImage imageWithContentsOfFile:[[self tj_refreshBundle] pathForResource:imageName ofType:@"png"]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
if(!image){
image = [[UIImage imageWithContentsOfFile:[[self tj_refreshBundle] pathForResource:[NSString stringWithFormat:@"%@@%dx",imageName,(int)[[UIScreen mainScreen]scale]] ofType:@"png"]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
}
return UIImagePNGRepresentation(image);;
}
- (NSBundle *)tj_refreshBundle
{
static NSBundle *refreshBundle = nil;
if (refreshBundle == nil) {
NSBundle *currentBundle = [NSBundle bundleForClass:[self class]];
refreshBundle = [NSBundle bundleWithPath:[currentBundle pathForResource:@"selfBundleName" ofType:@"bundle"]];
if(!refreshBundle){
refreshBundle = [NSBundle mainBundle];
}
}
return refreshBundle;
}
Android:
public Bitmap tj_imageName(String imageName) {
ApplicationInfo appInfo = BaseLibKit.getContext().getApplicationInfo();
int resID = BaseLibKit.getContext().getResources().getIdentifier(imageName, "drawable", appInfo.packageName);
Bitmap imageBitmap =
BitmapFactory.decodeResource(BaseLibKit.getContext().getResources(), resID);
return imageBitmap;
}
public byte[] getBitmapByte(Bitmap bitmap) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return out.toByteArray();
}
如果
bitmap.compress
第一个参数为Bitmap.CompressFormat.JPG
要注意图片资源是否有透明通道,如果有,透明通道会默认为黑色
- 以上是原生部分代码,根据图片名称获取图片二进制,通过
BasicMessageChannel
发送给Flutter,然后解析。 - 或者Fultter 部分发送获取图片通信消息,由原生回调回去。
使用 Uint8List? 类型接收
举例
Uint8List? _audio_icon_pause;
展示在组件上就是
child: (_audio_state_icon != null?
Image.memory(_audio_state_icon! ):
Image.network("defaultIcon")),
iOS 获取Flutter 资源图片
NSString* key = [registrar lookupKeyForAsset:@"assetsPath/imageName"];
NSString* path = [[NSBundle mainBundle] pathForResource:key ofType:nil];
Android 获取Flutter 资源图片
AssetManager assetManager = registrar.context().getAssets();
String key = registrar.lookupKeyForAsset("assetsPath/imageName");
AssetFileDescriptor fd = assetManager.openFd(key);