快照视图
创建视图快照
makeImageFromView
函数允许您将另一个 React Native 视图的快照作为 Skia SkImage 获取。该函数接受对原生视图的引用,并在成功时返回一个解析为 SkImage
实例的 Promise。
信息
在快照的根视图上使用 collapsable=false
更安全,以防止根视图被 React Native 删除。如果视图被优化掉,makeImageFromView
将会崩溃或返回错误的结果。
tsx
import {useState ,useRef } from "react";import {View ,Text ,PixelRatio ,StyleSheet ,Pressable } from "react-native";import type {SkImage } from "@shopify/react-native-skia";import {makeImageFromView ,Canvas ,Image } from "@shopify/react-native-skia";constpd =PixelRatio .get ();constDemo = () => {// Create a ref for the view you'd like to take a snapshot ofconstref =useRef <View >(null);// Create a state variable to store the snapshotconst [image ,setImage ] =useState <SkImage | null>(null);// Create a function to take the snapshotconstonPress = async () => {// Take the snapshot of the viewconstsnapshot = awaitmakeImageFromView (ref );setImage (snapshot );};return (<View style ={{flex : 1 }}><Pressable onPress ={onPress }><View ref ={ref }// collapsable={false} is important herecollapsable ={false}style ={{backgroundColor : "cyan",flex : 1 }}><Text >This is a React Native View</Text ></View ></Pressable >{image && (<Canvas style ={StyleSheet .absoluteFill }><Image image ={image }x ={0}y ={0}width ={image .width () /pd }height ={image .height () /pd }/></Canvas >)}</View >)};
tsx
import {useState ,useRef } from "react";import {View ,Text ,PixelRatio ,StyleSheet ,Pressable } from "react-native";import type {SkImage } from "@shopify/react-native-skia";import {makeImageFromView ,Canvas ,Image } from "@shopify/react-native-skia";constpd =PixelRatio .get ();constDemo = () => {// Create a ref for the view you'd like to take a snapshot ofconstref =useRef <View >(null);// Create a state variable to store the snapshotconst [image ,setImage ] =useState <SkImage | null>(null);// Create a function to take the snapshotconstonPress = async () => {// Take the snapshot of the viewconstsnapshot = awaitmakeImageFromView (ref );setImage (snapshot );};return (<View style ={{flex : 1 }}><Pressable onPress ={onPress }><View ref ={ref }// collapsable={false} is important herecollapsable ={false}style ={{backgroundColor : "cyan",flex : 1 }}><Text >This is a React Native View</Text ></View ></Pressable >{image && (<Canvas style ={StyleSheet .absoluteFill }><Image image ={image }x ={0}y ={0}width ={image .width () /pd }height ={image .height () /pd }/></Canvas >)}</View >)};