react-native-view-shot
一个库,允许你捕获 React Native 视图并将其保存为图片。
给定一个视图,captureRef
基本上会对该视图进行屏幕截图并为你返回图片。这对于签名板之类的东西非常有用,用户在其中绘制某些内容,然后你想从中保存图片。
¥Given a view, captureRef
will essentially screenshot that view and return an image for you. This is very useful for things like signature pads, where the user draws something, and then you want to save an image from it.
如果你有兴趣从 GLView 拍摄快照,我们建议你使用 GLView 的 takeSnapshotAsync。
¥If you're interested in taking snapshots from the GLView, we recommend you use GLView's takeSnapshotAsync instead.
安装
¥Installation
-
npx expo install react-native-view-shot
If you are installing this in an existing React Native app, make sure to install expo
in your project. Then, follow the installation instructions provided in the library's README or documentation.
注意像素值
¥Note on pixel values
请记住考虑设备 PixelRatio
。当你在 UI 中使用像素值时,大多数情况下这些单位是 "逻辑像素" 或 "与设备无关的像素"。对于 PNG 文件等图片,你经常使用 "物理像素"。你可以使用 React Native API 获取设备的 PixelRatio
:PixelRatio.get()
¥Remember to take the device PixelRatio
into account. When you work with pixel values in a UI, most of the time those units are "logical pixels" or "device-independent pixels". With images like PNG files, you often work with "physical pixels". You can get the PixelRatio
of the device using the React Native API: PixelRatio.get()
例如,要保存 1080x1080
的 'FullHD' 图片,你可以执行以下操作:
¥For example, to save a 'FullHD' picture of 1080x1080
, you would do something like this:
const targetPixelCount = 1080; // If you want full HD pictures
const pixelRatio = PixelRatio.get(); // The pixel ratio of the device
// pixels * pixelRatio = targetPixelCount, so pixels = targetPixelCount / pixelRatio
const pixels = targetPixelCount / pixelRatio;
const result = await captureRef(this.imageContainer, {
result: 'tmpfile',
height: pixels,
width: pixels,
quality: 1,
format: 'png',
});
了解更多
¥Learn more
获取有关 API 及其用法的完整信息。