最近一段时间在学习和实践React Native,针对与每篇官方教程做一些简单的注释记录。
Javascript示例的语法分析请见:Javascript for React Native语法教程 - GUIDE|Images
虽然英文一般,但学习新知识的时候还是习惯于直接啃英文文档,理由无他,有些中文翻译实在是太烂了,而且即使翻译水平尚可也有很多知识点描述的没有英文原生文档那么准确。因此在这里只做注释性的讲解,力求对英文文档的理解更容易但是不干扰其内容。因此在文末会提供英文文档阅读时我比较陌生的词,希望也能给你帮助。
图片组件的引用方式
<Image source={require(./img/check.png)} />
如何区分平台和分辨率
平台和分辨率可以在图片名称中指定,比较类似iOS上的做法:
- check.ios.png & check.android.png
- check@2x.png & check@3x.png
屏幕尺寸(dimensions)
Dimensions这个Package中提供了有关屏幕尺寸等相关信息的获取方法。例如获取屏幕宽度:
The packager knows the image dimensions, no need to duplicate in code.
bad code
// GOOD
<Image source={require(./my-icon.png)} />
// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />
// GOOD
var icon = this.props.active ? require('my-icon-active.png') : require('my-icon-inactive.png');
<Image source={icon} />
Hybird's App Images
没有安全检查机制,由外部确保这张图片已存在。
基于iOS的assets catalogs或者Anroid的drawable folder
<Image source={{uri: 'app_icon'}} style={{width: 40, height: 40}} />
网络图片的加载
网络图片是异步拉取的,只有图片拉取完成才能得到图片大小,因此为保证渲染时页面结构的清晰,React Native强制要求手动指定图片的尺寸。
// GOOD
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
style={{width: 400, height: 400}} />
// BAD
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />
读取本地文件系统的图片(相册图片)
如何获得最适合的照片尺寸
iOS在Camero Roll中保存了同一张照片的多个尺寸版本,因此基于性能的原因选择合适的分辨率变得非常重要。RN将根据当前指定的图片尺寸去找到尺寸一样的图片,如果没有符合的图片,那么RN会选择与当前尺寸接近的并且比当前图片大50%以上的那张图。这样做的原因是为了避免缩放图片时带来的模糊问题。上述行为由RN默认提供,不需要我们自定义。
指定其他视图的背景图片
React Native的视图组件设置背景图片的方式和Native有所不同,是通过在当前视图外包上一个Image组件实现的。
return (
<Image source={require('my-icon.png')}>
<Text>inside</Text>
</Image>
)
图片的离线解码
原文:Image decoding can take more than a frame-worth of time. This is one of the major source of frame drops on the web because decoding is done in the main thread. In React Native, image decoding is done in a different thread. In practice, you already need to handle the case when the image is not downloaded yet, so displaying the placeholder for a few more frames while it is decoding does not require any code change.
这部分没有理解很清楚,但可以确定image decoding在RN中放到异步线程中去做,应该会比Native decoding的performance更好。
Words
unified: 统一标准的
dimension: 尺寸