Error: width and height must be > 0 (on Android)
yaroslavnikiforov opened this issue · 1 comments
Describe the bug
Created a simple demo with the example code from README and it doesn't work. Either saveToPNG or saveToPNGBase64 throw an error: [Error: width and height must be > 0]
on Android. On iOS another error: [Error: ReactTag passed: 7]
.
Environment
software | version |
---|---|
react-native | 0.62.2 |
react-native-save-view | 0.2.3 |
device | Redmi Note 7 |
platform OS | Android 9 |
import React, {useEffect} from 'react';
import {View, Text} from 'react-native';
import RNSaveView from 'react-native-save-view';
export default class App extends React.Component {
render() {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<View
ref={ref => (this._viewRef = ref)}
collapsable={false}
style={{
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'pink',
width: 300,
height: 300,
}}>
<Text>Hello World</Text>
</View>
</View>
);
}
componentDidMount() {
this._saveView();
}
async _saveView() {
try {
await this._makeSnapshotPNG();
await this._makeSnapshotPNGBase64();
} catch (err) {
console.log('err', err);
}
}
async _makeSnapshotPNG() {
await RNSaveView.saveToPNG(this._viewRef, '/sdcard/Download/view.png');
// Check /sdcard/Download/view.png using Device File Explorer
}
async _makeSnapshotPNGBase64() {
const base64 = await RNSaveView.saveToPNGBase64(this._viewRef);
console.log('base64:', base64);
}
}
To Reproduce
- react-native init .
- npm i react-native-save-view.
- add the code above in App.js.
- npm run android
Additional context
Reproducible demo:
https://github.com/yaroslavnikiforov/react-native-save-view-demo
Hi @yaroslavnikiforov, thanks for demo project.
[Error: width and height must be > 0]
Means that component is not rendered properly yet. Small fix to your project:
$ git diff App.js
diff --git a/App.js b/App.js
index 83ce9c8..054c86f 100644
--- a/App.js
+++ b/App.js
@@ -31,7 +31,9 @@ export default class App extends React.Component {
}
componentDidMount() {
- this._saveView();
+ requestAnimationFrame(() => {
+ this._saveView();
+ });
}
fixes the issue.
Btw, you also need to configure permnissions to write the file, for example you can do it like this https://github.com/rumax/react-native-PDFView/blob/master/demo/android/app/src/main/java/com/demo/MainActivity.java#L31