238 lines
8.4 KiB
Plaintext
238 lines
8.4 KiB
Plaintext
/*
|
|
* Copyright (C) 2024 Huawei Device Co., Ltd.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
import {
|
|
CustomDataFetchClient,
|
|
DataFetchResult,
|
|
DownloadClient,
|
|
ImageKnifeComponent,
|
|
ImageKnifeGlobal,
|
|
ImageKnifeOption,
|
|
LogUtil,
|
|
ScaleType
|
|
} from '@ohos/libraryimageknife';
|
|
|
|
import http from '@ohos.net.http';
|
|
|
|
class CommonDataSource <T> implements IDataSource {
|
|
private dataArray: T[] = []
|
|
private listeners: DataChangeListener[] = []
|
|
|
|
constructor(element: []) {
|
|
this.dataArray = element
|
|
}
|
|
|
|
public getData(index: number) {
|
|
return this.dataArray[index]
|
|
}
|
|
|
|
public totalCount(): number {
|
|
return this.dataArray.length
|
|
}
|
|
|
|
public addData(index: number, data: T[]): void {
|
|
this.dataArray = this.dataArray.concat(data)
|
|
this.notifyDataAdd(index)
|
|
}
|
|
|
|
unregisterDataChangeListener(listener: DataChangeListener): void {
|
|
const pos = this.listeners.indexOf(listener);
|
|
if (pos >= 0) {
|
|
this.listeners.splice(pos, 1);
|
|
}
|
|
}
|
|
|
|
registerDataChangeListener(listener: DataChangeListener): void {
|
|
if (this.listeners.indexOf(listener) < 0) {
|
|
this.listeners.push(listener)
|
|
}
|
|
}
|
|
|
|
notifyDataAdd(index: number): void {
|
|
this.listeners.forEach((listener: DataChangeListener) => {
|
|
listener.onDataAdd(index)
|
|
})
|
|
}
|
|
}
|
|
|
|
@Entry
|
|
@Component
|
|
struct TestCustomDataFetchClientWithPage {
|
|
@State hotCommendList: CommonDataSource<string> = new CommonDataSource<string>([])
|
|
@State singleImageKnifeOption: ImageKnifeOption =
|
|
{
|
|
loadSrc: $r('app.media.icon'),
|
|
placeholderSrc: $r('app.media.icon_loading'),
|
|
errorholderSrc: $r('app.media.icon_failed'),
|
|
};
|
|
@State isSingleImageVisible: boolean = true;
|
|
@State isAllImageVisible: boolean = false;
|
|
@State isCustom: boolean = false;
|
|
private data: Array<string> = [
|
|
"http://img2.xkhouse.com/bbs/hfhouse/data/attachment/forum/corebbs/2009-11/2009113011534566298.jpg",
|
|
"http://a.hiphotos.baidu.com/image/pic/item/e824b899a9014c087eb617650e7b02087af4f464.jpg"
|
|
]
|
|
private addData: Array<string> = [
|
|
"http://c.hiphotos.baidu.com/image/pic/item/9c16fdfaaf51f3de1e296fa390eef01f3b29795a.jpg",
|
|
"http://h.hiphotos.baidu.com/image/pic/item/902397dda144ad340668b847d4a20cf430ad851e.jpg"
|
|
|
|
]
|
|
private cancelData: Array<string> = [
|
|
"http://b.hiphotos.baidu.com/image/pic/item/359b033b5bb5c9ea5c0e3c23d139b6003bf3b374.jpg",
|
|
"http://a.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a292d2472199d25bc315d607c7c.jpg"
|
|
]
|
|
|
|
aboutToAppear(): void {
|
|
this.hotCommendList.addData(this.hotCommendList.totalCount(), this.data)
|
|
LogUtil.log('TestCustomDataFetch about to appear.')
|
|
}
|
|
|
|
build() {
|
|
Scroll() {
|
|
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
|
|
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
|
|
|
|
Button("单个图片").margin(16).onClick(() => {
|
|
LogUtil.log('TestCustomDataFetch click single.');
|
|
this.isSingleImageVisible = true;
|
|
this.isAllImageVisible = false;
|
|
ImageKnifeGlobal.getInstance().getImageKnife()?.replaceDataFetch(new CustomDataFetchClient());
|
|
|
|
this.singleImageKnifeOption = {
|
|
loadSrc: 'http://e.hiphotos.baidu.com/image/pic/item/4e4a20a4462309f7e41f5cfe760e0cf3d6cad6ee.jpg',
|
|
placeholderSrc: $r('app.media.icon_loading'),
|
|
errorholderSrc: $r('app.media.icon_failed'),
|
|
customGetImage: custom
|
|
}
|
|
})
|
|
Button("全部图片").margin(16).onClick(() => {
|
|
LogUtil.log('TestCustomDataFetch click all.');
|
|
this.isSingleImageVisible = false;
|
|
this.isAllImageVisible = true;
|
|
|
|
ImageKnifeGlobal.getInstance().getImageKnife()?.replaceDataFetch(new CustomDataFetchClient());
|
|
this.hotCommendList.addData(this.hotCommendList.totalCount(), this.addData)
|
|
|
|
})
|
|
|
|
Button("取消自定义全部图片").margin(16).onClick(() => {
|
|
LogUtil.log('TestCustomDataFetch click cancel.');
|
|
this.isSingleImageVisible = false;
|
|
this.isAllImageVisible = true;
|
|
|
|
ImageKnifeGlobal.getInstance().getImageKnife()?.replaceDataFetch(new DownloadClient());
|
|
this.hotCommendList.addData(this.hotCommendList.totalCount(), this.cancelData)
|
|
})
|
|
}
|
|
|
|
// 单个图片使用自定义网络栈
|
|
ImageKnifeComponent({ imageKnifeOption: this.singleImageKnifeOption })
|
|
.width(200)
|
|
.height(200)
|
|
.margin({ top: 50 })
|
|
.visibility(this.isSingleImageVisible ? Visibility.Visible : Visibility.None)
|
|
|
|
// 全部图片使用自定义网络栈
|
|
Column() {
|
|
Grid() {
|
|
LazyForEach(this.hotCommendList, (item: string) => {
|
|
GridItem() {
|
|
ImageKnifeComponent({
|
|
imageKnifeOption: {
|
|
loadSrc: item,
|
|
placeholderSrc: $r('app.media.icon'),
|
|
errorholderSrc: $r('app.media.icon_failed'),
|
|
placeholderScaleType: ScaleType.CENTER_CROP,
|
|
mainScaleType: ScaleType.CENTER_CROP,
|
|
}
|
|
}).width('100%').height('100%')
|
|
}.width('40%').height(200)
|
|
}, (item: string) => JSON.stringify(item))
|
|
}
|
|
.columnsTemplate('1fr 1fr')
|
|
.columnsGap(8)
|
|
.rowsGap(10)
|
|
.width('100%')
|
|
.hitTestBehavior(HitTestMode.None)
|
|
.maxCount(10)
|
|
}.margin({ top: 5 })
|
|
.visibility(this.isAllImageVisible ? Visibility.Visible : Visibility.None)
|
|
}
|
|
}
|
|
.width('100%')
|
|
.height('100%')
|
|
}
|
|
}
|
|
|
|
@Concurrent
|
|
async function custom(context: Context, loadSrc: string): Promise<DataFetchResult> {
|
|
let result: DataFetchResult = new DataFetchResult();
|
|
try {
|
|
let arrayBuffers = new Array<ArrayBuffer>();
|
|
let httpRequest = http.createHttp()
|
|
httpRequest.on('headersReceive', (header: Object) => {
|
|
// 跟服务器连接成功准备下载
|
|
})
|
|
httpRequest.on('dataReceive', (data: ArrayBuffer) => {
|
|
// 下载数据流多次返回
|
|
arrayBuffers.push(data);
|
|
})
|
|
httpRequest.on('dataEnd', () => {
|
|
// 下载完毕
|
|
})
|
|
|
|
const resultCode = await httpRequest.requestInStream(loadSrc as string,
|
|
{
|
|
method: http.RequestMethod.GET,
|
|
expectDataType: http.HttpDataType.ARRAY_BUFFER,
|
|
connectTimeout: 60000, // 可选 默认60000ms
|
|
readTimeout: 0, // 可选, 默认为60000ms
|
|
usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
|
|
usingCache: false
|
|
}).catch((err: Error) => {
|
|
result.error = 'TestCustomDataFetchClientWithPage requestInStream error.' + JSON.stringify(err);
|
|
})
|
|
if (resultCode == 200) {
|
|
//let combineArray = this.combineArrayBuffers(arrayBuffers);
|
|
// 计算多个ArrayBuffer的总字节大小
|
|
let totalByteLength = 0;
|
|
for (const arrayBuffer of arrayBuffers) {
|
|
totalByteLength += arrayBuffer.byteLength;
|
|
}
|
|
// 创建一个新的ArrayBuffer
|
|
const combinedArrayBuffer = new ArrayBuffer(totalByteLength);
|
|
|
|
// 创建一个Uint8Array来操作新的ArrayBuffer
|
|
const combinedUint8Array = new Uint8Array(combinedArrayBuffer);
|
|
|
|
// 依次复制每个ArrayBuffer的内容到新的ArrayBuffer中
|
|
let offset = 0;
|
|
for (const arrayBuffer of arrayBuffers) {
|
|
const sourceUint8Array = new Uint8Array(arrayBuffer);
|
|
combinedUint8Array.set(sourceUint8Array, offset);
|
|
offset += sourceUint8Array.length;
|
|
}
|
|
result.data = combinedArrayBuffer;
|
|
} else {
|
|
result.error = 'TestCustomDataFetchClientWithPage error. resultCode = ' + resultCode;
|
|
}
|
|
console.log('TestCustomDataFetch single onComplete, code = ' + resultCode + ',length = ' + result.data?.byteLength);
|
|
} catch (error) {
|
|
result.error = 'TestCustomDataFetchClientWithPage error' + error.stack;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
|