Image
一个 React 组件,用于显示不同类型的图片,包括网络图片、静态资源、临时本地图片以及本地磁盘中的图片,例如相机胶卷。
¥A React component for displaying different types of images, including network images, static resources, temporary local images, and images from local disk, such as the camera roll.
此示例显示从本地存储以及网络甚至 'data:'
uri 方案中提供的数据获取和显示图片。
¥This example shows fetching and displaying an image from local storage as well as one from network and even from data provided in the 'data:'
uri scheme.
请注意,对于网络和数据图片,你将需要手动指定图片的尺寸!
¥Note that for network and data images, you will need to manually specify the dimensions of your image!
示例
¥Examples
你还可以将 style
添加到图片中:
¥You can also add style
to an image:
Android 上的 GIF 和 WebP 支持
¥GIF and WebP support on Android
构建你自己的原生代码时,Android 默认不支持 GIF 和 WebP。
¥When building your own native code, GIF and WebP are not supported by default on Android.
你将需要在 android/app/build.gradle
中添加一些可选模块,具体取决于你的应用的需求。
¥You will need to add some optional modules in android/app/build.gradle
, depending on the needs of your app.
dependencies {
// If your app supports Android versions before Ice Cream Sandwich (API level 14)
implementation 'com.facebook.fresco:animated-base-support:1.3.0'
// For animated GIF support
implementation 'com.facebook.fresco:animated-gif:3.1.3'
// For WebP support, including animated WebP
implementation 'com.facebook.fresco:animated-webp:3.1.3'
implementation 'com.facebook.fresco:webpsupport:3.1.3'
// For WebP support, without animations
implementation 'com.facebook.fresco:webpsupport:3.1.3'
}
注意:以上列出的版本可能不会及时更新。请检查主存储库中的
packages/react-native/gradle/libs.versions.toml
以查看特定标记版本中正在使用哪个 fresco 版本。¥Note: the version listed above may not be updated in time. Please check
packages/react-native/gradle/libs.versions.toml
in the main repo to see which fresco version is being used in a specific tagged version.
参考
¥Reference
属性
¥Props
视图属性
继承 视图属性。
¥Inherits View Props.
accessible
如果为 true,则表示图片是可访问性元素。
¥When true, indicates the image is an accessibility element.
类型 | 默认 |
---|---|
bool | false |
accessibilityLabel
当用户与图片交互时屏幕阅读器读取的文本。
¥The text that's read by the screen reader when the user interacts with the image.
类型 |
---|
string |
alt
定义图片的替代文本描述的字符串,当用户与其交互时,屏幕阅读器将读取该文本描述。使用它会自动将该元素标记为可访问。
¥A string that defines an alternative text description of the image, which will be read by the screen reader when the user interacts with it. Using this will automatically mark this element as accessible.
类型 |
---|
string |
blurRadius
模糊半径:添加到图片的模糊滤镜的模糊半径。
¥blurRadius: the blur radius of the blur filter added to the image.
类型 |
---|
number |
提示:在 IOS 上,你需要将
blurRadius
增加到5
以上。¥Tip: On IOS, you will need to increase
blurRadius
by more than5
.
capInsets
iOS
调整图片大小时,capInsets
指定大小的角点将保持固定大小,但图片的中心内容和边框将被拉伸。这对于创建可调整大小的圆形按钮、阴影和其他可调整大小的资源非常有用。更多信息请参见 苹果官方文档。
¥When the image is resized, the corners of the size specified by capInsets
will stay a fixed size, but the center content and borders of the image will be stretched. This is useful for creating resizable rounded buttons, shadows, and other resizable assets. More info in the official Apple documentation.
类型 |
---|
矩形 |
crossOrigin
指定获取图片资源时要使用的 CORS 模式的关键字字符串。它的工作原理类似于 HTML 中的 crossorigin 属性。
¥A string of a keyword specifying the CORS mode to use when fetching the image resource. It works similar to crossorigin attribute in HTML.
-
anonymous
:图片请求中不交换用户凭据。¥
anonymous
: No exchange of user credentials in the image request. -
use-credentials
:将图片请求中的Access-Control-Allow-Credentials
标头值设置为true
。¥
use-credentials
: SetsAccess-Control-Allow-Credentials
header value totrue
in the image request.
类型 | 默认 |
---|---|
enum('anonymous' , 'use-credentials' ) | 'anonymous' |
defaultSource
加载图片源时显示的静态图片。
¥A static image to display while loading the image source.
类型 |
---|
ImageSource |
注意:在 Android 上,调试版本中会忽略默认的 source 属性。
¥Note: On Android, the default source prop is ignored on debug builds.
fadeDuration
Android
淡入淡出动画持续时间(以毫秒为单位)。
¥Fade animation duration in milliseconds.
类型 | 默认 |
---|---|
number | 300 |
height
图片组件的高度。
¥Height of the image component.
类型 |
---|
number |
loadingIndicatorSource
与 source
类似,该属性表示用于渲染图片加载指示器的资源。加载指示符会一直显示,直到图片准备好显示为止,通常是在下载图片之后。
¥Similarly to source
, this property represents the resource used to render the loading indicator for the image. The loading indicator is displayed until image is ready to be displayed, typically after the image is downloaded.
类型 |
---|
ImageSource(仅限 uri ),数量 |
onError
加载错误时调用。
¥Invoked on load error.
类型 |
---|
({nativeEvent: {error} } ) => 无效 |
onLayout
在安装和布局更改时调用。
¥Invoked on mount and on layout changes.
类型 |
---|
({nativeEvent: LayoutEvent} => void |
onLoad
加载成功完成时调用。
¥Invoked when load completes successfully.
示例:onLoad={({nativeEvent: {source: {width, height}}}) => setImageRealSize({width, height})}
¥Example: onLoad={({nativeEvent: {source: {width, height}}}) => setImageRealSize({width, height})}
类型 |
---|
({nativeEvent: ImageLoadEvent} => void |
onLoadEnd
当加载成功或失败时调用。
¥Invoked when load either succeeds or fails.
类型 |
---|
() => 无效 |
onLoadStart
在加载开始时调用。
¥Invoked on load start.
示例:onLoadStart={() => this.setState({loading: true})}
¥Example: onLoadStart={() => this.setState({loading: true})}
类型 |
---|
() => 无效 |
onPartialLoad
iOS
当图片的部分加载完成时调用。"部分负载" 的构成定义是特定于加载程序的,尽管这适用于渐进式 JPEG 加载。
¥Invoked when a partial load of the image is complete. The definition of what constitutes a "partial load" is loader specific though this is meant for progressive JPEG loads.
类型 |
---|
() => 无效 |
onProgress
在下载进度时调用。
¥Invoked on download progress.
类型 |
---|
({nativeEvent: {loaded, total} } ) => 无效 |
progressiveRenderingEnabled
Android
当 true
时,启用渐进式 jpeg 流 - https://frescolib.org/docs/progressive-jpegs。
¥When true
, enables progressive jpeg streaming - https://frescolib.org/docs/progressive-jpegs.
类型 | 默认 |
---|---|
bool | false |
resizeMethod
Android
当图片的尺寸与图片视图的尺寸不同时,应该用于调整图片大小的机制。默认为 auto
。
¥The mechanism that should be used to resize the image when the image's dimensions differ from the image view's dimensions. Defaults to auto
.
-
auto
:使用启发法在resize
和scale
之间进行选择。¥
auto
: Use heuristics to pick betweenresize
andscale
. -
resize
:一种软件操作,可在解码之前更改内存中的编码图片。当图片比视图大得多时,应该使用它来代替scale
。¥
resize
: A software operation which changes the encoded image in memory before it gets decoded. This should be used instead ofscale
when the image is much larger than the view. -
scale
:图片被缩小或放大绘制。与resize
相比,scale
速度更快(通常是硬件加速)并产生更高质量的图片。如果图片小于视图,则应使用此方法。如果图片比视图稍大,也应该使用它。¥
scale
: The image gets drawn downscaled or upscaled. Compared toresize
,scale
is faster (usually hardware accelerated) and produces higher quality images. This should be used if the image is smaller than the view. It should also be used if the image is slightly bigger than the view.
有关 resize
和 scale
的更多详细信息,请参阅 https://frescolib.org/docs/resizing。
¥More details about resize
and scale
can be found at https://frescolib.org/docs/resizing.
类型 | 默认 |
---|---|
enum('auto' , 'resize' , 'scale' ) | 'auto' |
referrerPolicy
指示获取资源时使用哪个引用者的字符串。设置图片请求中 Referrer-Policy
标头的值。与 HTML 中的 referrerpolicy
属性类似。
¥A string indicating which referrer to use when fetching the resource. Sets the value for Referrer-Policy
header in the image request. Works similar to referrerpolicy
attribute in HTML.
类型 | 默认 |
---|---|
enum('no-referrer' , 'no-referrer-when-downgrade' , 'origin' , 'origin-when-cross-origin' , 'same-origin' , 'strict-origin' , 'strict-origin-when-cross-origin' , 'unsafe-url' ) | 'strict-origin-when-cross-origin' |
resizeMode
确定当框架与原始图片尺寸不匹配时如何调整图片大小。默认为 cover
。
¥Determines how to resize the image when the frame doesn't match the raw image dimensions. Defaults to cover
.
-
cover
:均匀缩放图片(保持图片的长宽比),以便¥
cover
: Scale the image uniformly (maintain the image's aspect ratio) so that-
图片的两个尺寸(宽度和高度)将等于或大于视图的相应尺寸(减去填充)
¥both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding)
-
缩放图片的至少一维将等于视图的相应尺寸(减去填充)
¥at least one dimension of the scaled image will be equal to the corresponding dimension of the view (minus padding)
-
-
contain
:均匀缩放图片(保持图片的纵横比),使图片的两个尺寸(宽度和高度)等于或小于视图的相应尺寸(减去填充)。¥
contain
: Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding). -
stretch
:独立缩放宽度和高度,这可能会改变 src 的纵横比。¥
stretch
: Scale width and height independently, This may change the aspect ratio of the src. -
repeat
:重复图片以覆盖视图的框架。图片将保持其大小和纵横比,除非它大于视图,在这种情况下,它将均匀缩小,以便包含在视图中。¥
repeat
: Repeat the image to cover the frame of the view. The image will keep its size and aspect ratio, unless it is larger than the view, in which case it will be scaled down uniformly so that it is contained in the view. -
center
:将图片在视图中沿两个维度居中。如果图片比视图大,则均匀缩小图片以使其包含在视图中。¥
center
: Center the image in the view along both dimensions. If the image is larger than the view, scale it down uniformly so that it is contained in the view.
类型 | 默认 |
---|---|
enum('cover' , 'contain' , 'stretch' , 'repeat' , 'center' ) | 'cover' |
source
图片源(远程 URL 或本地文件资源)。
¥The image source (either a remote URL or a local file resource).
此 prop 还可以包含多个远程 URL,与其宽度和高度一起指定,并可能与比例/其他 URI 参数一起指定。然后原生端会根据测量到的图片容器的大小选择最佳的 uri
来显示。可以添加 cache
属性来控制网络请求如何与本地缓存交互。(更多信息参见 图片缓存控制)。
¥This prop can also contain several remote URLs, specified together with their width and height and potentially with scale/other URI arguments. The native side will then choose the best uri
to display based on the measured size of the image container. A cache
property can be added to control how networked request interacts with the local cache. (For more information see Cache Control for Images).
当前支持的格式为 png
、jpg
、jpeg
、bmp
、gif
、webp
、psd
(仅限 iOS)。此外,iOS 支持多种 RAW 图片格式。请参阅 Apple 文档,了解当前支持的相机型号列表(对于 iOS 12,请参阅 https://support.apple.com/en-ca/HT208967)。
¥The currently supported formats are png
, jpg
, jpeg
, bmp
, gif
, webp
, psd
(iOS only). In addition, iOS supports several RAW image formats. Refer to Apple's documentation for the current list of supported camera models (for iOS 12, see https://support.apple.com/en-ca/HT208967).
类型 |
---|
ImageSource |
src
表示图片的远程 URL 的字符串。该属性优先于 source
属性。
¥A string representing the remote URL of the image. This prop has precedence over source
prop.
示例:src={'https://rn.nodejs.cn/img/tiny_logo.png'}
¥Example: src={'https://rn.nodejs.cn/img/tiny_logo.png'}
类型 |
---|
string |
srcSet
表示可能的候选图片源的逗号分隔列表的字符串。每个图片源包含图片的 URL 和像素密度描述符。如果没有指定描述符,则默认为 1x
的描述符。
¥A string representing comma separated list of possible candidate image source. Each image source contains a URL of an image and a pixel density descriptor. If no descriptor is specified, it defaults to descriptor of 1x
.
如果 srcSet
不包含 1x
描述符,则 src
中的值将用作具有 1x
描述符(如果提供)的图片源。
¥If srcSet
does not contain a 1x
descriptor, the value in src
is used as image source with 1x
descriptor (if provided).
该属性优先于 src
和 source
属性。
¥This prop has precedence over both the src
and source
props.
示例:srcSet={'https://rn.nodejs.cn/img/tiny_logo.png 1x, https://rn.nodejs.cn/img/header_logo.svg 2x'}
¥Example: srcSet={'https://rn.nodejs.cn/img/tiny_logo.png 1x, https://rn.nodejs.cn/img/header_logo.svg 2x'}
类型 |
---|
string |
style
类型 |
---|
图片样式属性、布局属性、影子属性、Transforms |
testID
该元素的唯一标识符将在 UI 自动化测试脚本中使用。
¥A unique identifier for this element to be used in UI Automation testing scripts.
类型 |
---|
string |
tintColor
将所有非透明像素的颜色更改为 tintColor
。
¥Changes the color of all non-transparent pixels to the tintColor
.
类型 |
---|
color |
width
图片组件的宽度。
¥Width of the image component.
类型 |
---|
number |
方法
¥Methods
abortPrefetch()
Android
static abortPrefetch(requestId: number);
中止预取请求。
¥Abort prefetch request.
参数:
¥Parameters:
名称 | 类型 | 描述 |
---|---|---|
requestId 必填 | number | prefetch() 返回的请求 ID。 |
getSize()
static getSize(
uri: string,
success: (width: number, height: number) => void,
failure?: (error: any) => void,
): any;
在显示图片之前检索图片的宽度和高度(以像素为单位)。如果找不到图片或下载失败,此方法可能会失败。
¥Retrieve the width and height (in pixels) of an image prior to displaying it. This method can fail if the image cannot be found, or fails to download.
为了检索图片尺寸,可能首先需要加载或下载图片,然后将其缓存。这意味着原则上你可以使用此方法来预加载图片,但它并未为此目的进行优化,并且将来可能会以不完全加载/下载图片数据的方式实现。预加载图片的正确且受支持的方法将作为单独的 API 提供。
¥In order to retrieve the image dimensions, the image may first need to be loaded or downloaded, after which it will be cached. This means that in principle you could use this method to preload images, however it is not optimized for that purpose, and may in future be implemented in a way that does not fully load/download the image data. A proper, supported way to preload images will be provided as a separate API.
参数:
¥Parameters:
类型 | 描述 | |
---|---|---|
uri 必填 | string | 图片的位置。 |
成功 必填 | function | 如果成功找到图片并检索宽度和高度,将调用该函数。 |
failure | function | 如果出现错误(例如无法检索图片),将调用该函数。 |
getSizeWithHeaders()
static getSizeWithHeaders(
uri: string,
headers: {[index: string]: string},
success: (width: number, height: number) => void,
failure?: (error: any) => void,
): any;
在显示图片之前检索图片的宽度和高度(以像素为单位),并能够为请求提供标头。如果找不到图片或下载失败,此方法可能会失败。它也不适用于静态图片资源。
¥Retrieve the width and height (in pixels) of an image prior to displaying it with the ability to provide the headers for the request. This method can fail if the image cannot be found, or fails to download. It also does not work for static image resources.
为了检索图片尺寸,可能首先需要加载或下载图片,然后将其缓存。这意味着原则上你可以使用此方法来预加载图片,但它并未为此目的进行优化,并且将来可能会以不完全加载/下载图片数据的方式实现。预加载图片的正确且受支持的方法将作为单独的 API 提供。
¥In order to retrieve the image dimensions, the image may first need to be loaded or downloaded, after which it will be cached. This means that in principle you could use this method to preload images, however it is not optimized for that purpose, and may in future be implemented in a way that does not fully load/download the image data. A proper, supported way to preload images will be provided as a separate API.
参数:
¥Parameters:
类型 | 描述 | |
---|---|---|
uri 必填 | string | 图片的位置。 |
标头 必填 | object | 请求的标头。 |
成功 必填 | function | 如果成功找到图片并检索宽度和高度,将调用该函数。 |
failure | function | 如果出现错误(例如无法检索图片),将调用该函数。 |
prefetch()
await Image.prefetch(url);
通过将远程图片下载到磁盘缓存来预取远程图片以供以后使用。返回一个解析为布尔值的 promise。
¥Prefetches a remote image for later use by downloading it to the disk cache. Returns a promise which resolves to a boolean.
参数:
¥Parameters:
名称 | 类型 | 描述 |
---|---|---|
url 必填 | string | 图片的远程位置。 |
callback | 函数 Android | 将使用 requestId 调用的函数。 |
queryCache()
static queryCache(
urls: string[],
): Promise<Record<string, 'memory' | 'disk' | 'disk/memory'>>;
执行缓存询问。返回一个 promise,该 promise 解析为从 URL 到缓存状态的映射,例如 "disk"、"memory" 或 "磁盘/内存"。如果请求的 URL 不在映射中,则意味着它不在缓存中。
¥Perform cache interrogation. Returns a promise which resolves to a mapping from URL to cache status, such as "disk", "memory" or "disk/memory". If a requested URL is not in the mapping, it means it's not in the cache.
参数:
¥Parameters:
名称 | 类型 | 描述 |
---|---|---|
url 必填 | array | 要检查缓存的图片 URL 列表。 |
resolveAssetSource()
static resolveAssetSource(source: ImageSourcePropType): {
height: number;
width: number;
scale: number;
uri: string;
};
将资源引用解析为具有属性 uri
、scale
、width
和 height
的对象。
¥Resolves an asset reference into an object which has the properties uri
, scale
, width
, and height
.
参数:
¥Parameters:
类型 | 描述 | |
---|---|---|
来源 必填 | ImageSource,号码 | 数字(require('./foo.png') 返回的不透明类型)或 ImageSource。 |
类型定义
¥Type Definitions
ImageCacheEnum iOS
枚举可用于设置潜在缓存响应的缓存处理或策略。
¥Enum which can be used to set the cache handling or stategy for the potentially cached responses.
类型 | 默认 |
---|---|
enum('default' , 'reload' , 'force-cache' , 'only-if-cached' ) | 'default' |
-
default
:使用原生平台默认策略。¥
default
: Use the native platforms default strategy. -
reload
:URL 的数据将从原始源加载。不应使用现有的缓存数据来满足 URL 加载请求。¥
reload
: The data for the URL will be loaded from the originating source. No existing cache data should be used to satisfy a URL load request. -
force-cache
:现有的缓存数据将用于满足请求,无论其年龄或到期日期如何。如果缓存中没有对应请求的现有数据,则从原始源加载数据。¥
force-cache
: The existing cached data will be used to satisfy the request, regardless of its age or expiration date. If there is no existing data in the cache corresponding the request, the data is loaded from the originating source. -
only-if-cached
:现有的缓存数据将用于满足请求,无论其年龄或到期日期如何。如果缓存中不存在与 URL 加载请求对应的数据,则不会尝试从原始源加载数据,并且加载被认为失败。¥
only-if-cached
: The existing cache data will be used to satisfy a request, regardless of its age or expiration date. If there is no existing data in the cache corresponding to a URL load request, no attempt is made to load the data from the originating source, and the load is considered to have failed.
ImageLoadEvent
onLoad
回调中返回的对象。
¥Object returned in the onLoad
callback.
类型 |
---|
object |
属性:
¥Properties:
名称 | 类型 | 描述 |
---|---|---|
source | object | 源对象 号 |
源对象
¥Source Object
属性:
¥Properties:
名称 | 类型 | 描述 |
---|---|---|
width | number | 加载图片的宽度。 |
height | number | 加载图片的高度。 |
uri | string | 表示图片的资源标识符的字符串。 |
ImageSource
类型 |
---|
对象、对象数组、数字 |
属性(如果作为对象或对象数组传递):
¥Properties (if passing as object or array of objects):
类型 | 描述 | |
---|---|---|
uri | string | 表示图片资源标识符的字符串,可以是 http 地址、本地文件路径或静态图片资源的名称。 |
width | number | 如果在构建时已知,则可以指定,在这种情况下,该值将用于设置默认的 <Image/> 组件尺寸。 |
height | number | 如果在构建时已知,则可以指定,在这种情况下,该值将用于设置默认的 <Image/> 组件尺寸。 |
scale | number | 用于表示图片的比例因子。如果未指定,则默认为 1.0 ,这意味着一个图片像素相当于一个显示点/DIP。 |
打包 iOS | string | 包含图片的 iOS 资源包。如果未设置,则默认为 [NSBundle mainBundle] 。 |
method | string | 要使用的 HTTP 方法。如果未指定,则默认为 'GET' 。 |
headers | object | 表示随远程图片请求一起发送的 HTTP 标头的对象。 |
body | string | 与请求一起发送的 HTTP 正文。这必须是有效的 UTF-8 字符串,并且将完全按照指定发送,不应用其他编码(例如 URL 转义或 base64)。 |
缓存 iOS | 图片缓存枚举 | 确定请求如何处理可能缓存的响应。 |
如果传递一个数字:
¥If passing a number:
-
number
- 由诸如require('./image.jpg')
之类的东西返回的不透明类型。¥
number
- opaque type returned by something likerequire('./image.jpg')
.