图片组件
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
用于展示各类图片的 React 组件,支持网络图片、静态资源、临时本地图片以及本地磁盘图片(如相册照片)。
此示例演示如何从本地存储获取并显示图片,同时也包含网络图片和使用 'data:' URI 方案的数据图片。
对于网络图片和数据图片,您需要手动指定图片尺寸!
使用示例
您也可以为图片添加 style 样式:
Android 平台对 GIF 和 WebP 的支持
在构建原生代码时,Android 默认不支持 GIF 和 WebP 格式。
您需要根据应用需求,在 android/app/build.gradle 中添加可选模块依赖。
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.6.0'
// For WebP support, including animated WebP
implementation 'com.facebook.fresco:animated-webp:3.6.0'
implementation 'com.facebook.fresco:webpsupport:3.6.0'
// For WebP support, without animations
implementation 'com.facebook.fresco:webpsupport:3.6.0'
}
上述列出的版本可能未及时更新。请查看主仓库的 packages/react-native/gradle/libs.versions.toml 文件,确认具体标签版本使用的 fresco 版本。
参考
属性
View 属性
继承 View 组件的属性。
accessible
设为 true 时表示该图片是可访问性元素。
| Type | Default |
|---|---|
| bool | false |
accessibilityLabel
屏幕阅读器在用户与图片交互时朗读的文本内容。
| Type |
|---|
| string |
alt
定义图片替代文本的字符串,屏幕阅读器将在用户交互时朗读该描述。使用此属性会自动将元素标记为可访问。
| Type |
|---|
| string |
blurRadius
blurRadius:应用于图片的模糊滤镜半径值。
| Type |
|---|
| number |
在 iOS 平台,您需要将 blurRadius 设置为大于 5 的值。
capInsets iOS
当图片调整尺寸时,由 capInsets 定义的边角区域将保持固定尺寸,而图片中心内容和边框会被拉伸。此特性适用于创建可伸缩的圆角按钮、阴影等资源。更多信息请参阅苹果官方文档。
| Type |
|---|
| Rect |
crossOrigin
指定获取图片资源时使用的 CORS 模式关键字字符串,功能类似 HTML 中的 crossorigin 属性。
-
anonymous:图片请求中不携带用户凭证 -
use-credentials:在图片请求中将Access-Control-Allow-Credentials标头值设为true
| Type | Default |
|---|---|
enum('anonymous', 'use-credentials') | 'anonymous' |
defaultSource
加载图片源时显示的静态占位图。
| Type |
|---|
| ImageSource |
在 Android 平台,调试版本会忽略 defaultSource 属性。
fadeDuration Android
淡入动画持续时间(毫秒)。
| Type | Default |
|---|---|
| number | 300 |
height
图片组件的高度值。
| Type |
|---|
| number |
loadingIndicatorSource
与 source 类似,该属性表示用于渲染图片加载指示器的资源。加载指示器会持续显示,直到图片准备就绪(通常为下载完成后)才被替换。
| Type |
|---|
ImageSource (uri only), number |
onError
加载失败时触发。
| Type |
|---|
({nativeEvent: {error} }) => void |
onLayout
在挂载时和布局变化时触发。
| Type |
|---|
({nativeEvent: LayoutEvent} => void |
onLoad
加载成功完成时触发。
示例: onLoad={({nativeEvent: {source: {width, height}}}) => setImageRealSize({width, height})}
| Type |
|---|
({nativeEvent: ImageLoadEvent} => void |
onLoadEnd
加载成功或失败时均会触发。
| Type |
|---|
| () => void |
onLoadStart
开始加载时触发。
示例: onLoadStart={() => this.setState({loading: true})}
| Type |
|---|
| () => void |
onPartialLoad iOS
当图片部分加载完成时触发。具体"部分加载"的定义取决于加载器实现,常用于渐进式 JPEG 加载场景。
| Type |
|---|
| () => void |
onProgress
下载进度变化时触发。
| Type |
|---|
({nativeEvent: {loaded, total} }) => void |
progressiveRenderingEnabled Android
设为 true 时启用渐进式 JPEG 流式加载 - 详见 https://frescolib.org/docs/progressive-jpegs。
| Type | Default |
|---|---|
| bool | false |
referrerPolicy
指定获取资源时使用的 referrer 策略字符串。设置图片请求中 Referrer-Policy 头的值,功能类似于 HTML 中的 referrerpolicy 属性。
| Type | Default |
|---|---|
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' |
ref
一个在组件挂载时会被赋予元素节点的 ref 设置器。
resizeMethod Android
当图片尺寸与视图尺寸不匹配时,用于指定图片缩放机制。默认为 auto。
-
auto: 自动在resize和scale间选择最佳方案 -
resize: 在内存中对编码图像进行预处理后再解码。当图片远大于视图时应优先使用此模式而非scale -
scale: 直接对图像进行缩放绘制。相比resize,scale速度更快(通常硬件加速)且画质更高。适用于图片小于或略大于视图的场景 -
none: 不进行采样处理,直接以原始分辨率显示。仅在极少数场景使用(可能导致 Android 因内存溢出抛出运行时异常)
更多关于 resize 和 scale 的细节详见 https://frescolib.org/docs/resizing。
| Type | Default |
|---|---|
enum('auto', 'resize', 'scale', 'none') | 'auto' |
resizeMode
定义当图片框架与原始图片尺寸不匹配时的缩放方式,默认为 cover。
-
cover: 等比例缩放(保持宽高比),确保:- 图像宽高均 ≥ 视图对应维度(减去内边距)
- 至少有一个维度 = 视图对应维度(减去内边距)
-
contain: 等比例缩放(保持宽高比),图片的宽高都将小于或等于视图对应维度(减去内边距) -
stretch: 独立缩放宽度和高度,可能改变原始图片宽高比 -
repeat: 重复图片以铺满视图区域。图片保持原始尺寸和宽高比,若大于视图则等比例缩小至能被视图包含 -
center: 在视图中双轴居中显示。若图片大于视图,则等比例缩小至能被视图包含
| Type | Default |
|---|---|
enum('cover', 'contain', 'stretch', 'repeat', 'center') | 'cover' |
resizeMultiplier Android
当 resizeMethod 设置为 resize 时,目标尺寸会乘以该值。scale 方法用于执行剩余的缩放操作。默认值 1.0 表示位图尺寸设计为适应目标尺寸。大于 1.0 的乘数会将缩放选项设置为大于目标尺寸,最终位图会从硬件尺寸向下缩放。默认为 1.0。
该属性在目标尺寸较小而源图像较大的场景特别有用。resize 缩放方法执行下采样时,源图像与目标图像尺寸之间会显著损失图像质量,通常导致图像模糊。通过使用乘数,解码后的图像会略大于目标尺寸但小于源图像(如果源图像足够大)。这允许缩放操作在放大后的图像上利用混叠效应模拟出更高质量。
例如:源图像尺寸为 200x200,目标尺寸为 24x24。若设置 resizeMultiplier 为 2.0,Fresco 会将图像下采样至 48x48。Fresco 会选择最接近的 2 的幂次方尺寸(即 50x50)并将图像解码为该尺寸的位图。若不使用乘数,最接近的 2 的幂次方尺寸会是 25x25,最终图像由系统进行缩小处理。
| Type | Default |
|---|---|
| number | 1.0 |
source
图像源(可以是远程 URL 或本地文件资源)。
该属性也可包含多个远程 URL,同时指定其宽度、高度以及可能的缩放比例/其他 URI 参数。原生端会根据图像容器的测量尺寸自动选择最佳 uri 进行显示。可添加 cache 属性控制网络请求与本地缓存的交互方式(详见图像缓存控制)。
当前支持的格式包括 png、jpg、jpeg、bmp、gif、webp、psd (仅限 iOS)。此外,iOS 支持多种 RAW 图像格式。具体支持的相机型号请参考苹果官方文档 (iOS 12 详见 https://support.apple.com/en-ca/HT208967).
注意:webp 格式在 iOS 上仅在与 JavaScript 代码捆绑时才受支持。
| Type |
|---|
| ImageSource |
src
表示图像远程 URL 的字符串。该属性优先级高于 source 属性。
示例: src={'https://reactnative.dev/img/tiny_logo.png'}
| Type |
|---|
| string |
srcSet
表示候选图像源列表的字符串(以逗号分隔)。每个图像源包含图像 URL 和像素密度描述符。若未指定描述符,则默认为 1x。
如果 srcSet 不包含 1x 描述符,则使用 src 的值作为 1x 描述符的图像源(若提供)。
该属性优先级高于 src 和 source 属性。
示例: srcSet={'https://reactnative.dev/img/tiny_logo.png 1x, https://reactnative.dev/img/header_logo.svg 2x'}
| Type |
|---|
| string |
style
testID
用于 UI 自动化测试脚本中标识此元素的唯一标识符。
| Type |
|---|
| string |
tintColor
将所有非透明像素的颜色更改为 tintColor。
| Type |
|---|
| color |
width
图像组件的宽度。
| Type |
|---|
| number |
方法
abortPrefetch() Android
static abortPrefetch(requestId: number);
中止预取请求。
参数:
| Name | Type | Description |
|---|---|---|
| requestId Required | number | Request id as returned by prefetch(). |
getSize()
static getSize(uri: string): Promise<{width: number, height: number}>;
在显示图像前获取其宽度和高度(以像素为单位)。如果图像无法找到或下载失败,此方法可能会失败。
要获取图像尺寸,可能需要先加载或下载图像(随后会被缓存)。理论上可用此方法预加载图像,但这不是其优化目的,未来实现可能不会完全加载/下载图像数据。预加载图像将通过独立 API 提供专门支持。
参数:
Name | Type | Description |
|---|---|---|
| uri Required | string | The location of the image. |
getSizeWithHeaders()
static getSizeWithHeaders(
uri: string,
headers: {[index: string]: string}
): Promise<{width: number, height: number}>;
在显示图像前获取其宽度和高度(以像素为单位),可提供请求头信息。如果图像无法找到或下载失败,此方法可能会失败。不适用于静态图像资源。
要获取图像尺寸,可能需要先加载或下载图像(随后会被缓存)。理论上可用此方法预加载图像,但这不是其优化目的,未来实现可能不会完全加载/下载图像数据。预加载图像将通过独立 API 提供专门支持。
参数:
Name | Type | Description |
|---|---|---|
| uri Required | string | The location of the image. |
| headers Required | object | The headers for the request. |
prefetch()
await Image.prefetch(url);
预取远程图像以供后续使用(下载至磁盘缓存)。返回解析为布尔值的 Promise。
参数:
| Name | Type | Description |
|---|---|---|
| url Required | string | The remote location of the image. |
| callback | function Android | The function that will be called with the requestId. |
queryCache()
static queryCache(
urls: string[],
): Promise<Record<string, 'memory' | 'disk' | 'disk/memory'>>;
执行缓存查询。返回解析为 URL 到缓存状态映射的 Promise,状态如 "disk"、"memory" 或 "disk/memory"。若请求的 URL 不在映射中,表示未缓存。
参数:
| Name | Type | Description |
|---|---|---|
| urls Required | array | List of image URLs to check the cache for. |
resolveAssetSource()
static resolveAssetSource(source: ImageSourcePropType): {
height: number;
width: number;
scale: number;
uri: string;
};
将资源引用解析为包含 uri、scale、width 和 height 属性的对象。
参数:
Name | Type | Description |
|---|---|---|
| source Required | ImageSource, number | A number (opaque type returned by require('./foo.png')) or an ImageSource. |
类型定义
ImageCacheEnum iOS
用于设置缓存响应处理策略的枚举。
| Type | Default |
|---|---|
enum('default', 'reload', 'force-cache', 'only-if-cached') | 'default' |
-
default:使用平台默认策略 -
reload:直接从源地址加载数据,不使用任何缓存数据 -
force-cache:优先使用缓存数据(无论是否过期),仅当缓存不存在时才从源地址加载 -
only-if-cached:仅使用缓存数据(无论是否过期),若缓存不存在则直接视为加载失败
ImageLoadEvent
onLoad 回调返回的对象。
| Type |
|---|
| object |
属性:
| Name | Type | Description |
|---|---|---|
| source | object | The source object |
源对象
属性:
| Name | Type | Description |
|---|---|---|
| width | number | The width of loaded image. |
| height | number | The height of loaded image. |
| uri | string | A string representing the resource identifier for the image. |
ImageSource
| Type |
|---|
| object, array of objects, number |
属性(当传递对象或对象数组时):
Name | Type | Description |
|---|---|---|
| uri | string | A string representing the resource identifier for the image, which could be an http address, a local file path, or the name of a static image resource. |
| width | number | Can be specified if known at build time, in which case the value will be used to set the default <Image/> component dimension. |
| height | number | Can be specified if known at build time, in which case the value will be used to set the default <Image/> component dimension. |
| scale | number | Used to indicate the scale factor of the image. Defaults to 1.0 if unspecified, meaning that one image pixel equates to one display point / DIP. |
| bundle iOS | string | The iOS asset bundle which the image is included in. This will default to [NSBundle mainBundle] if not set. |
| method | string | The HTTP Method to use. Defaults to 'GET' if not specified. |
| headers | object | An object representing the HTTP headers to send along with the request for a remote image. |
| body | string | The HTTP body to send with the request. This must be a valid UTF-8 string, and will be sent exactly as specified, with no additional encoding (e.g. URL-escaping or base64) applied. |
| cache iOS | ImageCacheEnum | Determines how the requests handles potentially cached responses. |
如果传递的是数字:
number- 由类似require('./image.jpg')的表达式返回的不透明类型。