Skip to main content

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

视图属性

¥View Props

继承 视图属性

¥Inherits View Props.


accessible

如果为 true,则表示图片是可访问性元素。

¥When true, indicates the image is an accessibility element.

类型默认
boolfalse

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 than 5.


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: Sets Access-Control-Allow-Credentials header value to true 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.

类型默认
number300

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.

类型默认
boolfalse

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'

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:使用启发法在 resizescale 之间进行选择。

    ¥auto: Use heuristics to pick between resize and scale.

  • resize:一种软件操作,可在解码之前更改内存中的编码图片。当图片比视图大得多时,应该使用它来代替 scale

    ¥resize: A software operation which changes the encoded image in memory before it gets decoded. This should be used instead of scale when the image is much larger than the view.

  • scale:图片被缩小或放大绘制。与 resize 相比,scale 速度更快(通常是硬件加速)并产生更高质量的图片。如果图片小于视图,则应使用此方法。如果图片比视图稍大,也应该使用它。

    ¥scale: The image gets drawn downscaled or upscaled. Compared to resize, 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.

  • none:不执行采样,图片以其全分辨率显示。这只应在极少数情况下使用,因为它被认为是不安全的,因为 Android 在尝试渲染消耗过多内存的图片时会抛出运行时异常。

    ¥none: No sampling is performed and the image is displayed in its full resolution. This should only be used in rare circumstances because it is considered unsafe as Android will throw a runtime exception when trying to render images that consume too much memory.

有关 resizescale 的更多详细信息,请参阅 https://frescolib.org/docs/resizing

¥More details about resize and scale can be found at https://frescolib.org/docs/resizing.

类型默认
enum('auto', 'resize', 'scale', 'none')'auto'

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'

resizeMultiplier
Android

resizeMethod 设置为 resize 时,目标尺寸将乘以此值。scale 方法用于执行调整大小的其余部分。1.0 的默认值表示位图大小设计为适合目标尺寸。大于 1.0 的乘数将设置调整大小选项大于目标尺寸,并且生成的位图将从硬件尺寸缩小。默认为 1.0

¥When the resizeMethod is set to resize, the destination dimensions are multiplied by this value. The scale method is used to perform the remainder of the resize. A default of 1.0 means the bitmap size is designed to fit the destination dimensions. A multiplier greater than 1.0 will set the resize options larger than that of the destination dimensions, and the resulting bitmap will be scaled down from the hardware size. Defaults to 1.0.

此 prop 在目标尺寸非常小而源图片明显较大的情况下最有用。resize 调整大小方法执行下采样,源图片大小和目标图片大小之间会显著损失图片质量,通常会导致图片模糊。通过使用乘数,解码后的图片略大于目标大小但小于源图片(如果源图片足够大)。这允许通过对乘法图片进行缩放操作,使别名伪像产生虚假质量。

¥This prop is most useful in cases where the destination dimensions are quite small and the source image is significantly larger. The resize resize method performs downsampling and significant image quality is lost between the source and destination image sizes, often resulting in a blurry image. By using a multiplier, the decoded image is slightly larger than the target size but smaller than the source image (if the source image is large enough). This allows aliasing artifacts to produce faux quality through scaling operations on the multiplied image.

如果你有一个尺寸为 200x200 的源图片和尺寸为 24x24 的目标图片,那么 2.0 的 resizeMultiplier 将告诉 Fresco 将图片下采样到 48x48。Fresco 选择最接近的 2 的幂(因此,50x50)并将图片解码为该大小的位图。如果没有乘数,最接近的 2 的幂将是 25x25。生成的图片由系统缩小。

¥If you have a source image with dimensions 200x200 and destination dimensions of 24x24, a resizeMultiplier of 2.0 will tell Fresco to downsample the image to 48x48. Fresco picks the closest power of 2 (so, 50x50) and decodes the image into a bitmap of that size. Without the multiplier, the closest power of 2 would be 25x25. The resultant image is scaled down by the system.

类型默认
number1.0

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).

当前支持的格式为 pngjpgjpegbmpgifwebppsd(仅限 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).

请注意,只有与 JavaScript 代码打包在一起时,iOS 才支持 webp 格式。

¥Please note that the webp format is supported on iOS only when bundled with the JavaScript code.

类型
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).

该属性优先于 srcsource 属性。

¥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
必填
numberprefetch() 返回的请求 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如果成功找到图片并检索宽度和高度,将调用该函数。
failurefunction如果出现错误(例如无法检索图片),将调用该函数。

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如果成功找到图片并检索宽度和高度,将调用该函数。
failurefunction如果出现错误(例如无法检索图片),将调用该函数。

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;
};

将资源引用解析为具有属性 uriscalewidthheight 的对象。

¥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 strategy 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:

名称类型描述
sourceobject源对象

源对象

¥Source Object

属性:

¥Properties:

名称类型描述
widthnumber加载图片的宽度。
heightnumber加载图片的高度。
uristring表示图片的资源标识符的字符串。

ImageSource

类型
对象、对象数组、数字

属性(如果作为对象或对象数组传递):

¥Properties (if passing as object or array of objects):

类型描述
uristring表示图片资源标识符的字符串,可以是 http 地址、本地文件路径或静态图片资源的名称。
widthnumber如果在构建时已知,则可以指定,在这种情况下,该值将用于设置默认的 <Image/> 组件尺寸。
heightnumber如果在构建时已知,则可以指定,在这种情况下,该值将用于设置默认的 <Image/> 组件尺寸。
scalenumber用于表示图片的比例因子。如果未指定,则默认为 1.0,这意味着一个图片像素相当于一个显示点/DIP。
打包
iOS
string包含图片的 iOS 资源包。如果未设置,则默认为 [NSBundle mainBundle]
methodstring要使用的 HTTP 方法。如果未指定,则默认为 'GET'
headersobject表示随远程图片请求一起发送的 HTTP 标头的对象。
bodystring与请求一起发送的 HTTP 正文。这必须是有效的 UTF-8 字符串,并且将完全按照指定发送,不应用其他编码(例如 URL 转义或 base64)。
缓存
iOS
图片缓存枚举确定请求如何处理可能缓存的响应。

如果传递一个数字:

¥If passing a number:

  • number - 由诸如 require('./image.jpg') 之类的东西返回的不透明类型。

    ¥number - opaque type returned by something like require('./image.jpg').