[TOC]
源碼解讀RCTImageView(iOS)
查看官網(wǎng)自定義UI組件的文檔, 可以知道每個(gè)自定義的UI組件CustomView
需要對應(yīng)一個(gè)CustomViewManager
, CustomViewManager
繼承RCTViewManager
.
我們可以跟蹤查看requireNativeComponent的實(shí)現(xiàn)赁酝, 最終發(fā)現(xiàn)調(diào)用的是UIManager.createView(...), 對應(yīng)原生RCTUIManager的createView方法。
一、RCTUIManager的原理
原生
- RCTUIManager也是一個(gè)module, 在setBridge的時(shí)候瓦盛, 獲取bridge中所有RCTViewManager的子類保存下來
- (void)setBridge:(RCTBridge *)bridge {
...
for (Class moduleClass in _bridge.moduleClasses) {
if ([moduleClass isSubclassOfClass:[RCTViewManager class]]) {
RCTComponentData *componentData = [[RCTComponentData alloc] initWithManagerClass:moduleClass
bridge:_bridge];
componentDataByName[componentData.name] = componentData;
}
}
_componentDataByName = [componentDataByName copy];
...
}
- constantsToExport把所有相關(guān)ViewManager的信息導(dǎo)出
- (NSDictionary<NSString *, id> *)constantsToExport
{
...
return constants;
}
具體信息格式為:
{
...
RCTImageView = {
Manager = ImageViewManager;
NativeProps = {
blurRadius = CGFloat;
capInsets = UIEdgeInsets;
defaultSource = UIImage;
onError = BOOL;
onLoad = BOOL;
onLoadEnd = BOOL;
onLoadStart = BOOL;
onPartialLoad = BOOL;
onProgress = BOOL;
resizeMode = RCTResizeMode;
source = "NSArray<RCTImageSource *>";
tintColor = UIColor;
};
};
RCTWebView = {
Manager = WebViewManager;
NativeProps = {
allowsInlineMediaPlayback = BOOL;
automaticallyAdjustContentInsets = BOOL;
bounces = BOOL;
contentInset = UIEdgeInsets;
dataDetectorTypes = UIDataDetectorTypes;
decelerationRate = CGFloat;
injectedJavaScript = NSString;
mediaPlaybackRequiresUserAction = BOOL;
messagingEnabled = BOOL;
onLoadingError = BOOL;
onLoadingFinish = BOOL;
onLoadingStart = BOOL;
onMessage = BOOL;
onShouldStartLoadWithRequest = BOOL;
scalesPageToFit = BOOL;
scrollEnabled = BOOL;
source = NSDictionary;
};
};
customBubblingEventTypes = {
topBlur = {
phasedRegistrationNames = {
bubbled = onBlur;
captured = onBlurCapture;
};
};
topChange = {
phasedRegistrationNames = {
bubbled = onChange;
captured = onChangeCapture;
};
};
...
};
customDirectEventTypes = {
topAccessibilityTap = {
registrationName = onAccessibilityTap;
};
topError = {
registrationName = onError;
};
...
};
...
}
每個(gè)對應(yīng)的UI組件 xxxView有manager、NativeProps倆個(gè)屬性外潜。分別表示對應(yīng)的ViewManager及屬性原环。
JS
//UIManager.js
// 經(jīng)過映射 UIManager是一個(gè)帶有上述jsonkey的對象。 同時(shí) 會增加Constants 與 UIManager的屬性处窥。
UIManager 數(shù)據(jù)結(jié)構(gòu)
RCTImageView
原生類的關(guān)系圖:
js部分
//Image.ios.js
const Image = createReactClass({...,
render:function() {
...
return (
<RCTImageView
{...this.props}
style={style}
resizeMode={resizeMode}
tintColor={tintColor}
source={sources}
/>
);
}
});
...
const RCTImageView = requireNativeComponent('RCTImageView', Image);
module.exports = Image;
圖片定位
Image的圖片瀏覽主要通過source設(shè)置嘱吗, js傳遞source信息體到原生, 原生根據(jù)source信息體生成對應(yīng)的請求碧库, 通過遍歷所有實(shí)現(xiàn)的RCTImageURLLoader協(xié)議的模塊柜与,選擇最優(yōu)的loader獲取image,如果沒有則嘗試使用網(wǎng)絡(luò)接口獲取嵌灰,失敗則報(bào)錯(cuò)弄匕。 流程如下
source的解析
RN的Image控件,支持2種形式的source
- require('filepath') //PropTypes.number
- {uri:'fileURI', bundle:'bundleName', width:100, height:100, ... } //ImageURISourcePropType
圖片控件的JS代碼對應(yīng)Image.ios.js, 原生代碼對應(yīng)RCTImageView
require方式
require方式返回的是一個(gè)整型沽瞭, 對應(yīng)一個(gè)define函數(shù), 在bundle中體現(xiàn)為
//引用的地方 require方式
_react2.default.createElement(_reactNative.Image, { source: require(305 ), __source: { // 305 = ./Images/diary_mood_icon_alcohol_32.png
fileName: _jsxFileName,
lineNumber: 30
}
}),
// uri 方式
_react2.default.createElement(_reactNative.Image, { source: { uir: 'https://www.baidu.com/img/bd_logo1.png', width: 100, height: 100 }, __source: {
fileName: _jsxFileName,
lineNumber: 31
}
})
//define地方
__d(/* RN472/Images/diary_mood_icon_alcohol_32.png */function(global, require, module, exports) {module.exports=require(161 ).registerAsset({"__packager_asset":true,"httpServerLocation":"/assets/Images","width":16,"height":16,"scales":[2,3],"hash":"7824b2f2a263b0bb181ff482a88fb813","name":"diary_mood_icon_alcohol_32","type":"png"}); // 161 = react-native/Libraries/Image/AssetRegistry
}, 305, null, "RN472/Images/diary_mood_icon_alcohol_32.png");
我們看到打包的時(shí)候迁匠,require圖片會轉(zhuǎn)換成如下格式的對象保存:
{
"__packager_asset":true, //是否是asset目錄下的資源
"httpServerLocation":"/assets/Images", //server目錄地址
"width":16,
"height":16,
"scales":[2,3], //圖片scales
"hash":"7824b2f2a263b0bb181ff482a88fb813", //文件hash值
"name":"diary_mood_icon_alcohol_32", //文件名
"type":"png" //文件類型
}
我們看到引用的地方require(305)其實(shí)是執(zhí)行了require(161)的registerAsset的方法。查看161的define
__d(/* AssetRegistry */function(global, require, module, exports) {
'use strict';
var assets = [];
function registerAsset(asset) {
return assets.push(asset);
}
function getAssetByID(assetId) {
return assets[assetId - 1];
}
module.exports = { registerAsset: registerAsset, getAssetByID: getAssetByID };
}, 161, null, "AssetRegistry");
161對應(yīng)的就是AssetRegistry驹溃, AssetRegistry.registerAsset把圖片信息保存在成員數(shù)組assets中城丧。
查看Image.ios.js的render函數(shù)
render: function() {
const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined };
...
return (
<RCTImageView
{...this.props}
style={style}
resizeMode={resizeMode}
tintColor={tintColor}
source={sources}
/>
);
通過resolveAssetSource函數(shù)
function resolveAssetSource(source: any): ?ResolvedAssetSource {
if (typeof source === 'object') {
return source;
}
var asset = AssetRegistry.getAssetByID(source);
if (!asset) {
return null;
}
const resolver = new AssetSourceResolver(getDevServerURL(), getBundleSourcePath(), asset);
if (_customSourceTransformer) {
return _customSourceTransformer(resolver);
}
return resolver.defaultAsset();
調(diào)用AssetRegistry.getAssetByID方法取出對應(yīng)的信息,傳遞到原生豌鹤。
//傳遞到原生的source信息格式
{
"__packager_asset" = 1;
height = 16;
scale = 2;
uri = "http://Users/huangmingwei/Library/Developer/CoreSimulator/Devices/2A0C4BE4-807B-4000-83EB-342B720A14DE/data/Containers/Bundle/Application/F84F1359-CBCD-4184-B3FD-2C7833B83A60/RN472.app/react-app/assets/Images/diary_mood_icon_alcohol_32@2x.png";
width = 16;
}
原生通過解析uri信息亡哄,獲取對應(yīng)的圖片
//RCTImageView.m
- (void)setImageSources:(NSArray<RCTImageSource *> *)imageSources
{
if (![imageSources isEqual:_imageSources]) {
_imageSources = [imageSources copy];
[self reloadImage];
}
}
原生加載過程涉到及幾個(gè)類
- RCTImageSource, 通過js傳遞的source信息,轉(zhuǎn)換出圖片地址
- RCTImageViewManager 管理RCTImageView
- RCTImageVIew 對應(yīng)每個(gè)Image實(shí)例
- RCTImageLoader bridge的成員布疙,控制圖片的加載邏輯
- RCTImageURLLoader 協(xié)議蚊惯,具體圖片的定位執(zhí)行者需要實(shí)現(xiàn)此協(xié)議
- RCTLocalAssetImageLoader 實(shí)現(xiàn)bundle統(tǒng)計(jì)目錄asset下的圖片訪問 loader
重點(diǎn)在RCTImageURLLoader協(xié)議
//判斷能否處理
- (BOOL)canLoadImageURL:(NSURL *)requestURL;
//獲取圖片, 如果是異步處理返回一個(gè)可以取消的block
- (RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
size:(CGSize)size
scale:(CGFloat)scale
resizeMode:(RCTResizeMode)resizeMode
progressHandler:(RCTImageLoaderProgressBlock)progressHandler
partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
completionHandler:(RCTImageLoaderCompletionBlock)completionHandler;
URI方式
這種方式的加載流程與require相同灵临,只是source的獲取信息方式比較簡單截型,js端設(shè)置的是什么,到原生端也是一樣
function resolveAssetSource(source: any): ?ResolvedAssetSource {
if (typeof source === 'object') { // uri 方式直接返回
return source;
}
原生通過RCTImageSource解析流程是一樣的儒溉。
Array方式
js端最終將source轉(zhuǎn)換為一個(gè)Array宦焦,傳遞到原生。如果有多個(gè)uri顿涣,可設(shè)置為不同尺寸的圖片波闹,在原生會選擇大小最適合的一個(gè)圖片展示。 當(dāng)只有一張圖片的時(shí)候园骆,默認(rèn)會轉(zhuǎn)為只有一個(gè)元素的Array舔痪。目前都是只有一張哦~
RCTImageView.m
- (RCTImageSource *)imageSourceForSize:(CGSize)size
{
if (![self hasMultipleSources]) {
return _imageSources.firstObject;
}
// Need to wait for layout pass before deciding.
if (CGSizeEqualToSize(size, CGSizeZero)) {
return nil;
}
const CGFloat scale = RCTScreenScale();
const CGFloat targetImagePixels = size.width * size.height * scale * scale;
RCTImageSource *bestSource = nil;
CGFloat bestFit = CGFLOAT_MAX;
for (RCTImageSource *source in _imageSources) {
CGSize imgSize = source.size;
const CGFloat imagePixels =
imgSize.width * imgSize.height * source.scale * source.scale;
const CGFloat fit = ABS(1 - (imagePixels / targetImagePixels));
if (fit < bestFit) {
bestFit = fit;
bestSource = source;
}
}
return bestSource;
}