Revert "ComponentV2装饰器适配"

Signed-off-by: zgf <zenggaofeng2@h-partners.com>
This commit is contained in:
zgf 2024-09-30 14:39:19 +08:00
parent ecb7540d6f
commit 4e7a26eef1
39 changed files with 340 additions and 605 deletions

View File

@ -1,3 +1,15 @@
## 3.0.2
- ImageKnifeAnimatorComponent新增开始、结束、暂停的回调事件
- 文件缓存数量负数和超过INT最大值时默认为INT最大值
- 修复宽高不等svg图片显示有毛边
- 部分静态webp图片有delay属性导致识别成动图,改用getFrameCount识别
- 修复加载错误图后未去请求排队队列中的请求
- 子线程本地Resource参数类型转换成number
- 修改使用hilog记录日志默认打开debug级别的日志
- 解码pixelMap默认不可编辑图形变化可编辑
- 修改网络请求超时设置
- 重构代码抽取ImageKnifeDispatcher子线程requestJob相关代码到ImageKnifeLoader中降低函数复杂度
## 3.0.2-rc.1 ## 3.0.2-rc.1
- release打包关闭混淆 - release打包关闭混淆

View File

@ -12,82 +12,44 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import { AnimatorOption, ImageKnifeAnimatorComponent,ImageKnifeOption } from "@ohos/libraryimageknife" import { AnimatorOption, ImageKnifeAnimatorComponent } from "@ohos/libraryimageknife"
@Entry @Entry
@ComponentV2 @Component
struct ImageAnimatorPage { struct ImageAnimatorPage {
@Local animatorOption: AnimatorOption = new AnimatorOption({ @State animatorOption: AnimatorOption = {
state: AnimationStatus.Running, state: AnimationStatus.Running,
iterations: -1, iterations: -1
onFinish:()=>{ }
console.log("ImageKnifeAnimatorComponent animatorOption onFinish")
},
onStart:()=>{
console.log("ImageKnifeAnimatorComponent animatorOption onStart")
},
onPause:()=>{
console.log("ImageKnifeAnimatorComponent animatorOption onPause")
},
onCancel:()=>{
console.log("ImageKnifeAnimatorComponent animatorOption onCancel")
},
onRepeat:()=>{
console.log("ImageKnifeAnimatorComponent animatorOption onRepeat")
}
})
@Local animatorOption1: AnimatorOption = new AnimatorOption({
state: AnimationStatus.Initial
})
@Local animatorOption2: AnimatorOption = new AnimatorOption({
state: AnimationStatus.Initial,
reverse: true
})
build() { build() {
Column(){ Column(){
Flex(){ Flex(){
Button($r('app.string.Play')).onClick(()=>{ Button("播放").onClick(()=>{
this.animatorOption.state = AnimationStatus.Running this.animatorOption.state = AnimationStatus.Running
}) })
Button($r('app.string.Pause')).onClick(()=>{ Button("暂停").onClick(()=>{
this.animatorOption.state = AnimationStatus.Paused this.animatorOption.state = AnimationStatus.Paused
}) })
Button($r('app.string.Stop')).onClick(()=>{ Button("停止").onClick(()=>{
this.animatorOption.state = AnimationStatus.Stopped this.animatorOption.state = AnimationStatus.Stopped
}) })
Button($r('app.string.Infinite_loop')).onClick(()=>{ Button("无限循环").onClick(()=>{
this.animatorOption.iterations = -1 this.animatorOption.iterations = -1
}) })
Button($r('app.string.Play_once')).onClick(()=>{ Button("播放一次").onClick(()=>{
this.animatorOption.iterations = 1 this.animatorOption.iterations = 1
}) })
Button($r('app.string.Play_twice')).onClick(()=>{ Button("播放两次").onClick(()=>{
this.animatorOption.iterations = 2 this.animatorOption.iterations = 2
}) })
} }
ImageKnifeAnimatorComponent({ ImageKnifeAnimatorComponent({
imageKnifeOption:new ImageKnifeOption({ imageKnifeOption:{
loadSrc:"https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658", loadSrc:"https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658",
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed') errorholderSrc:$r('app.media.failed')
}),animatorOption:this.animatorOption },animatorOption:this.animatorOption
}).width(200).height(200).backgroundColor(Color.Orange).margin({top:30}) }).width(300).height(300).backgroundColor(Color.Orange).margin({top:30})
Text($r('app.string.Display_the_first_frame')).fontSize(20)
ImageKnifeAnimatorComponent({
imageKnifeOption:new ImageKnifeOption({
loadSrc:"https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658",
placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed')
}),animatorOption:this.animatorOption1
}).width(200).height(200).backgroundColor(Color.Orange).margin({top:30})
Text($r('app.string.Display_the_last_frame')).fontSize(20)
ImageKnifeAnimatorComponent({
imageKnifeOption:new ImageKnifeOption({
loadSrc:"https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658",
placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed')
}),animatorOption:this.animatorOption2
}).width(200).height(200).backgroundColor(Color.Orange).margin({top:30})
}.width("100%").height("100%") }.width("100%").height("100%")
} }
} }

View File

@ -35,17 +35,17 @@ import {
import { collections } from '@kit.ArkTS' import { collections } from '@kit.ArkTS'
@Entry @Entry
@ComponentV2 @Component
struct ImageTransformation { struct ImageTransformation {
@Local imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption: ImageKnifeOption = {
loadSrc: $r('app.media.pngSample'), loadSrc: $r('app.media.pngSample'),
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"), errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Contain objectFit: ImageFit.Contain
}) }
@Local isRound: boolean = false; @State isRound: boolean = false;
@Local isContrast: boolean = false; @State isContrast: boolean = false;
@Local isRotate: boolean = false; @State isRotate: boolean = false;
isBlur: boolean = false isBlur: boolean = false
isBrightness: boolean = false isBrightness: boolean = false
isGrayScale: boolean = false; isGrayScale: boolean = false;
@ -412,14 +412,14 @@ struct ImageTransformation {
if (this.isMask) { if (this.isMask) {
transformations.push(new MaskTransformation($r('app.media.mask_starfish'))); transformations.push(new MaskTransformation($r('app.media.mask_starfish')));
} }
this.imageKnifeOption = new ImageKnifeOption({ this.imageKnifeOption = {
loadSrc: $r('app.media.pngSample'), loadSrc: $r('app.media.pngSample'),
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"), errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Contain, objectFit: ImageFit.Contain,
border: { radius: this.isRound ? { topLeft: 50, bottomRight: 50 } : 0 }, border: { radius: this.isRound ? { topLeft: 50, bottomRight: 50 } : 0 },
transformation: transformations.length > 0 ? new MultiTransTransformation(transformations) : undefined transformation: transformations.length > 0 ? new MultiTransTransformation(transformations) : undefined
}) }
if (this.isCropCircle) { if (this.isCropCircle) {
this.imageKnifeOption.objectFit = ImageFit.Cover; this.imageKnifeOption.objectFit = ImageFit.Cover;
this.imageKnifeOption.border = { radius: 150 }; this.imageKnifeOption.border = { radius: 150 };

View File

@ -15,7 +15,7 @@
import router from '@system.router'; import router from '@system.router';
@Entry @Entry
@ComponentV2 @Component
struct Index { struct Index {
getResourceString(res:Resource){ getResourceString(res:Resource){

View File

@ -15,11 +15,11 @@
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/libraryimageknife'; import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/libraryimageknife';
@Entry @Entry
@ComponentV2 @Component
struct ListPage { struct ListPage {
private data: string[] = [] private data: string[] = []
@Local ImageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ loadSrc: $r('app.media.startIcon')}) @State ImageKnifeOption: ImageKnifeOption = { loadSrc: $r('app.media.startIcon')}
aboutToAppear(): void { aboutToAppear(): void {

View File

@ -16,12 +16,12 @@ import { ImageKnifeComponent, ImageKnifeOption } from "@ohos/libraryimageknife"
import matrix4 from '@ohos.matrix4' import matrix4 from '@ohos.matrix4'
@Entry @Entry
@ComponentV2 @Component
struct LoadStatePage { struct LoadStatePage {
starTime:number = new Date().getTime() starTime:number = new Date().getTime()
@Local ImageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ @State ImageKnifeOption: ImageKnifeOption = {
loadSrc: $r("app.media.rabbit"), loadSrc: $r("app.media.rabbit"),
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"), errorholderSrc: $r("app.media.app_icon"),
@ -35,22 +35,22 @@ struct LoadStatePage {
}, },
}, },
border: { radius: 50 } border: { radius: 50 }
}) }
@Local imageKnifeOption1: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption1: ImageKnifeOption = {
loadSrc: $r('app.media.startIcon') loadSrc: $r('app.media.startIcon')
}) }
@Local message: string = "" @State message: string = ""
@Local currentWidth: number = 200 @State currentWidth: number = 200
@Local currentHeight: number = 200 @State currentHeight: number = 200
@Local typeValue: string = "" @State typeValue: string = ""
build() { build() {
Column() { Column() {
Text($r('app.string.TIPS')) Text('测试失败场景请先关闭网络,并保证本地没有此网络图片的缓存')
.margin({ top: 20 }) .margin({ top: 20 })
Row() { Row() {
Button($r('app.string.Test_failure_success')) Button('测试失败/成功场景')
.onClick(() => { .onClick(() => {
this.ImageKnifeOption = new ImageKnifeOption({ this.ImageKnifeOption = {
loadSrc: "https://www.openharmony.cn/_nuxt/img/logo.dcf95b3.png", loadSrc: "https://www.openharmony.cn/_nuxt/img/logo.dcf95b3.png",
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"), errorholderSrc: $r("app.media.app_icon"),
@ -75,15 +75,15 @@ struct LoadStatePage {
onComplete:(event)=>{ onComplete:(event)=>{
console.error("Load onComplete width:"+event?.width , " height:"+event?.height , " componentWidth:"+event?.componentWidth," componentHeight:" + event?.componentHeight); console.error("Load onComplete width:"+event?.width , " height:"+event?.height , " componentWidth:"+event?.componentWidth," componentHeight:" + event?.componentHeight);
} }
}) }
}) })
} }
.margin({ top: 20 }) .margin({ top: 20 })
Text(this.typeValue) Text(this.typeValue)
ImageKnifeComponent({ imageKnifeOption: this.ImageKnifeOption }).height(this.currentHeight).width(this.currentWidth) ImageKnifeComponent({ imageKnifeOption: this.ImageKnifeOption }).height(this.currentHeight).width(this.currentWidth)
.margin({ top: 20 }) .margin({ top: 20 })
Button($r('app.string.Custom_download_failed')).onClick(()=>{ Button("自定义下载失败").onClick(()=>{
this.imageKnifeOption1 = new ImageKnifeOption({ this.imageKnifeOption1 = {
loadSrc: "abc", loadSrc: "abc",
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed'), errorholderSrc:$r('app.media.failed'),
@ -93,7 +93,7 @@ struct LoadStatePage {
this.message = "err:" + err this.message = "err:" + err
} }
} }
}) }
}).margin({ top: 20 }) }).margin({ top: 20 })
Text(this.message).fontSize(20).margin({ top: 20 }) Text(this.message).fontSize(20).margin({ top: 20 })
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).height(this.currentHeight).width(this.currentWidth) ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).height(this.currentHeight).width(this.currentWidth)

View File

@ -12,10 +12,10 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import { ImageKnifeComponent,ImageKnifeOption } from '@ohos/libraryimageknife' import { ImageKnifeComponent } from '@ohos/libraryimageknife'
@Entry @Entry
@ComponentV2 @Component
struct LongImagePage { struct LongImagePage {
build() { build() {
@ -25,13 +25,13 @@ struct LongImagePage {
// Image($r("app.media.aaa")).objectFit(ImageFit.Auto).width(200) // Image($r("app.media.aaa")).objectFit(ImageFit.Auto).width(200)
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc:"https://wx2.sinaimg.cn/mw690/006HyQKGgy1hnqp08dw09j30u04twu0x.jpg", loadSrc:"https://wx2.sinaimg.cn/mw690/006HyQKGgy1hnqp08dw09j30u04twu0x.jpg",
//src:$r("app.media.aaa"), //src:$r("app.media.aaa"),
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.failed"), errorholderSrc: $r("app.media.failed"),
objectFit: ImageFit.Auto objectFit: ImageFit.Auto
}) }
}) })
} }
.height('100%') .width('100%') .height('100%') .width('100%')

View File

@ -12,12 +12,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import { BlurTransformation, ImageKnifeComponent,ImageKnifeOption } from '@ohos/libraryimageknife'; import { ImageKnifeComponent } from '@ohos/libraryimageknife';
@Entry @Entry
@ComponentV2 @Component
struct ManyPhotoShowPage { struct ManyPhotoShowPage {
private data: TestDataSource = new TestDataSource(); private data: TestDataSource = new TestDataSource();
@ -36,16 +36,15 @@ struct ManyPhotoShowPage {
// loadSrc: item.thumbnail, // loadSrc: item.thumbnail,
// mainScaleType: ScaleType.FIT_XY, // mainScaleType: ScaleType.FIT_XY,
// } }) // } })
ImageKnifeComponent({imageKnifeOption:new ImageKnifeOption({ ImageKnifeComponent({imageKnifeOption:{
loadSrc: item.thumbnail, loadSrc: item.thumbnail,
//src:"https://www.openharmony.cn/_nuxt/img/logo.dcf95b3.png", //src:"https://www.openharmony.cn/_nuxt/img/logo.dcf95b3.png",
// src: this.localFile, // src: this.localFile,
placeholderSrc:$r("app.media.loading"), placeholderSrc:$r("app.media.loading"),
errorholderSrc:$r("app.media.failed"), errorholderSrc:$r("app.media.failed"),
objectFit: ImageFit.Auto, objectFit: ImageFit.Auto,
border: {radius:50}, border: {radius:50}
transformation:new BlurTransformation(5) }})
})})
} }
.width(56).height(56) .width(56).height(56)
//滤镜标题 //滤镜标题

View File

@ -15,49 +15,49 @@
import { ImageKnife, ImageKnifeComponent, ImageKnifeOption } from '@ohos/libraryimageknife' import { ImageKnife, ImageKnifeComponent, ImageKnifeOption } from '@ohos/libraryimageknife'
@Entry @Entry
@ComponentV2 @Component
struct ObjectFitPage { struct ObjectFitPage {
@Local imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption: ImageKnifeOption = {
loadSrc: $r("app.media.app_icon"), loadSrc: $r("app.media.app_icon"),
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"), errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Fill objectFit: ImageFit.Fill
}) }
build() { build() {
Column() { Column() {
Button($r('app.string.Main_image_Fill')).onClick(()=>{ Button("主图Fill拉伸填充").onClick(()=>{
this.imageKnifeOption = new ImageKnifeOption({ this.imageKnifeOption = {
loadSrc: $r("app.media.app_icon"), loadSrc: $r("app.media.app_icon"),
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"), errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Fill objectFit: ImageFit.Fill
}) }
}) })
Button($r('app.string.Maintain_proportion_filling')).margin({top:10}).onClick(async () => { Button("占位图Contain保持比例填充").margin({top:10}).onClick(async () => {
ImageKnife.getInstance().removeAllMemoryCache() ImageKnife.getInstance().removeAllMemoryCache()
await ImageKnife.getInstance().removeAllFileCache() await ImageKnife.getInstance().removeAllFileCache()
this.imageKnifeOption = new ImageKnifeOption({ this.imageKnifeOption = {
loadSrc: "https://wx2.sinaimg.cn/mw690/006HyQKGgy1hnqp08dw09j30u04twu0x.jpg", loadSrc: "https://wx2.sinaimg.cn/mw690/006HyQKGgy1hnqp08dw09j30u04twu0x.jpg",
placeholderSrc: $r("app.media.app_icon"), placeholderSrc: $r("app.media.app_icon"),
errorholderSrc: $r("app.media.app_icon"), errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Fill, objectFit: ImageFit.Fill,
placeholderObjectFit: ImageFit.Contain placeholderObjectFit: ImageFit.Contain
}) }
}) })
Button($r('app.string.Error_graph_None')).margin({top:10}).onClick(() => { Button("错误图None不变化").margin({top:10}).onClick(() => {
this.imageKnifeOption = new ImageKnifeOption({ this.imageKnifeOption = {
loadSrc: "http://xxxxx", loadSrc: "http://xxxxx",
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"), errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Fill, objectFit: ImageFit.Fill,
errorholderObjectFit: ImageFit.None errorholderObjectFit: ImageFit.None
}) }
}) })
ImageKnifeComponent({ ImageKnifeComponent({

View File

@ -16,18 +16,18 @@ import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/libraryimageknife';
@Entry @Entry
@ComponentV2 @Component
struct SignatureTestPage { struct SignatureTestPage {
@Local imageKnifeOption1: ImageKnifeOption =new ImageKnifeOption( @State imageKnifeOption1: ImageKnifeOption =
{ {
loadSrc: $r('app.media.icon'), loadSrc: $r('app.media.icon'),
placeholderSrc:$r("app.media.loading"), placeholderSrc:$r("app.media.loading"),
}); };
@Local imageKnifeOption2: ImageKnifeOption =new ImageKnifeOption( @State imageKnifeOption2: ImageKnifeOption =
{ {
loadSrc: $r('app.media.icon'), loadSrc: $r('app.media.icon'),
placeholderSrc:$r("app.media.loading"), placeholderSrc:$r("app.media.loading"),
}); };
build() { build() {
Scroll() { Scroll() {
@ -37,11 +37,11 @@ struct SignatureTestPage {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button($r('app.string.Load')) Button($r('app.string.Load'))
.onClick(() => { .onClick(() => {
this.imageKnifeOption1 = new ImageKnifeOption({ this.imageKnifeOption1 = {
loadSrc: 'https://img-blog.csdn.net/20140514114029140', loadSrc: 'https://img-blog.csdn.net/20140514114029140',
placeholderSrc:$r("app.media.loading"), placeholderSrc:$r("app.media.loading"),
signature: "1" signature: "1"
}) }
}).margin({ top: 5, left: 3 }) }).margin({ top: 5, left: 3 })
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).width(300).height(300) ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).width(300).height(300)
}.width('100%').backgroundColor(Color.Pink) }.width('100%').backgroundColor(Color.Pink)
@ -50,11 +50,11 @@ struct SignatureTestPage {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button($r('app.string.Load')) Button($r('app.string.Load'))
.onClick(() => { .onClick(() => {
this.imageKnifeOption2 = new ImageKnifeOption({ this.imageKnifeOption2 = {
loadSrc: 'https://img-blog.csdn.net/20140514114029140', loadSrc: 'https://img-blog.csdn.net/20140514114029140',
placeholderSrc:$r("app.media.loading"), placeholderSrc:$r("app.media.loading"),
signature: new Date().getTime().toString() signature: new Date().getTime().toString()
}) }
}).margin({ top: 5, left: 3 }) }).margin({ top: 5, left: 3 })
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption2 }).width(300).height(300) ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption2 }).width(300).height(300)
}.width('100%').backgroundColor(Color.Pink) }.width('100%').backgroundColor(Color.Pink)

View File

@ -12,19 +12,19 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import { ImageKnifeComponent,BlurTransformation,ImageKnifeOption } from '@ohos/libraryimageknife'; import { ImageKnifeComponent,BlurTransformation } from '@ohos/libraryimageknife';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
import { common2D, drawing } from '@kit.ArkGraphics2D'; import { common2D, drawing } from '@kit.ArkGraphics2D';
@Entry @Entry
@ComponentV2 @Component
struct SingleImage { struct SingleImage {
resource: string = "app.media.svgSample" resource: string = "app.media.svgSample"
scroller: Scroller = new Scroller; scroller: Scroller = new Scroller;
localFile: string = getContext(this).filesDir + "/icon.png" localFile: string = getContext(this).filesDir + "/icon.png"
@Local pixelMap:PixelMap | undefined = undefined; @State pixelMap:PixelMap | undefined = undefined;
@Local DrawingColorFilter: ColorFilter | undefined = undefined @State DrawingColorFilter: ColorFilter | undefined = undefined
private color: common2D.Color = { alpha: 255, red: 255, green: 0, blue: 0 }; private color: common2D.Color = { alpha: 255, red: 255, green: 0, blue: 0 };
aboutToAppear(): void { aboutToAppear(): void {
// 拷贝本地文件 // 拷贝本地文件
@ -46,12 +46,12 @@ struct SingleImage {
.fontSize(30) .fontSize(30)
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc: $r("app.media.svgSample"), loadSrc: $r("app.media.svgSample"),
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.failed"), errorholderSrc: $r("app.media.failed"),
objectFit: ImageFit.Contain objectFit: ImageFit.Contain
}) }
}).width(100).height(100) }).width(100).height(100)
.onClick(()=>{ .onClick(()=>{
this.DrawingColorFilter = drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN); this.DrawingColorFilter = drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
@ -60,48 +60,48 @@ struct SingleImage {
.fontSize(30) .fontSize(30)
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc: this.localFile, loadSrc: this.localFile,
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.failed"), errorholderSrc: $r("app.media.failed"),
objectFit: ImageFit.Contain objectFit: ImageFit.Contain
}) }
}).width(100).height(100) }).width(100).height(100)
Text($r('app.string.Network_images')) Text($r('app.string.Network_images'))
.fontSize(30) .fontSize(30)
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc:"https://www.openharmony.cn/_nuxt/img/logo.dcf95b3.png", loadSrc:"https://www.openharmony.cn/_nuxt/img/logo.dcf95b3.png",
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.failed"), errorholderSrc: $r("app.media.failed"),
objectFit: ImageFit.Contain, objectFit: ImageFit.Contain,
progressListener:(progress:number)=>{console.info("ImageKnife:: call back progress = " + progress)} progressListener:(progress:number)=>{console.info("ImageKnife:: call back progress = " + progress)}
}) }
}).width(100).height(100) }).width(100).height(100)
Text($r('app.string.Custom_network_download')) Text($r('app.string.Custom_network_download'))
.fontSize(30) .fontSize(30)
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc: "https://file.atomgit.com/uploads/user/1704857786989_8994.jpeg", loadSrc: "https://file.atomgit.com/uploads/user/1704857786989_8994.jpeg",
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.failed"), errorholderSrc: $r("app.media.failed"),
objectFit: ImageFit.Contain, objectFit: ImageFit.Contain,
customGetImage: custom, customGetImage: custom,
transformation: new BlurTransformation(10) transformation: new BlurTransformation(10)
}) }
}).width(100).height(100) }).width(100).height(100)
Text($r('app.string.PixelMap_loads_images')) Text($r('app.string.PixelMap_loads_images'))
.fontSize(30) .fontSize(30)
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc: this.pixelMap!, loadSrc: this.pixelMap!,
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.failed"), errorholderSrc: $r("app.media.failed"),
objectFit: ImageFit.Contain, objectFit: ImageFit.Contain,
}) }
}).width(100).height(100) }).width(100).height(100)
} }
.width('100%') .width('100%')

View File

@ -12,10 +12,10 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import { ImageKnifeComponent ,ImageKnifeOption} from '@ohos/libraryimageknife'; import { ImageKnifeComponent } from '@ohos/libraryimageknife';
@Entry @Entry
@ComponentV2 @Component
struct TestCommonImage { struct TestCommonImage {
private data: Array<string> = [] private data: Array<string> = []
aboutToAppear(): void { aboutToAppear(): void {
@ -30,13 +30,13 @@ struct TestCommonImage {
FlowItem() { FlowItem() {
Column(){ Column(){
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc: item, loadSrc: item,
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.failed"), errorholderSrc: $r("app.media.failed"),
objectFit: ImageFit.Contain, objectFit: ImageFit.Contain,
signature: "aaa" signature: "aaa"
}) }
}).width("50%").height(200) }).width("50%").height(200)
} }
}.height(200) }.height(200)

View File

@ -12,34 +12,34 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import { ImageKnifeComponent,ImageKnifeOption } from '@ohos/libraryimageknife' import { ImageKnifeComponent } from '@ohos/libraryimageknife'
@Entry @Entry
@ComponentV2 @Component
struct TestErrorHolderPage { struct TestErrorHolderPage {
build() { build() {
Column() { Column() {
Text("ImageKnifeComponent1").fontSize(20) Text("ImageKnifeComponent1").fontSize(20)
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc: "abc", loadSrc: "abc",
errorholderSrc:$r('app.media.failed') errorholderSrc:$r('app.media.failed')
}) }
}).width(200).height(200) }).width(200).height(200)
Text("ImageKnifeComponent2").fontSize(20) Text("ImageKnifeComponent2").fontSize(20)
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc: "abc", loadSrc: "abc",
errorholderSrc:$r('app.media.startIcon') errorholderSrc:$r('app.media.startIcon')
}) }
}).width(200).height(200) }).width(200).height(200)
Text("ImageKnifeComponent2").fontSize(20) Text("ImageKnifeComponent2").fontSize(20)
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc: "abc", loadSrc: "abc",
errorholderSrc:$r('app.media.mask_starfish') errorholderSrc:$r('app.media.mask_starfish')
}) }
}).width(200).height(200) }).width(200).height(200)
} }
.height('100%') .width('100%') .height('100%') .width('100%')

View File

@ -15,9 +15,9 @@
import { ImageKnifeComponent,ImageKnifeOption } from '@ohos/libraryimageknife' import { ImageKnifeComponent,ImageKnifeOption } from '@ohos/libraryimageknife'
@Entry @Entry
@ComponentV2 @Component
struct TestPrefetchToFileCachePage { struct TestPrefetchToFileCachePage {
@Local imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption: ImageKnifeOption = {
loadSrc:"https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658", loadSrc:"https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658",
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
headerOption:[ headerOption:[
@ -26,7 +26,7 @@ struct TestPrefetchToFileCachePage {
value:"单个" value:"单个"
} }
] ]
}) }
build() { build() {
Column() { Column() {

View File

@ -15,7 +15,7 @@
import { IndexComponent } from "@ohos/libraryimageknife" import { IndexComponent } from "@ohos/libraryimageknife"
@Entry @Entry
@ComponentV2 @Component
struct TestHspPreLoadImage { struct TestHspPreLoadImage {
build() { build() {
Column() { Column() {

View File

@ -12,9 +12,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import { ImageKnifeComponent,ImageKnifeOption } from '@ohos/libraryimageknife' import { ImageKnifeComponent } from '@ohos/libraryimageknife'
@ObservedV2 @Observed
export class MsgModel { export class MsgModel {
id: string id: string
cId: string cId: string
@ -30,10 +30,10 @@ export class MsgModel {
} }
// @Reusable @Reusable
@ComponentV2 @Component
export struct MsgItem { export struct MsgItem {
@Param count: number = 0 count: number = 0
private data: Array<string> = [ private data: Array<string> = [
"http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg", "http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
"http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg", "http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg",
@ -59,37 +59,37 @@ export struct MsgItem {
build(){ build(){
if (this.count % 2 == 0 && this.count <6){ if (this.count % 2 == 0 && this.count <6){
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption:new ImageKnifeOption({ imageKnifeOption:{
loadSrc:$r("app.media.startIcon"), loadSrc:$r("app.media.startIcon"),
placeholderSrc:$r("app.media.loading") placeholderSrc:$r("app.media.loading")
}),syncLoad:true },syncLoad:true
}) })
}else if (this.count > 6 && this.count - 6 < this.data.length){ }else if (this.count > 6 && this.count - 6 < this.data.length){
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption:new ImageKnifeOption({ imageKnifeOption:{
loadSrc:this.data[this.count - 6], loadSrc:this.data[this.count - 6],
placeholderSrc:$r("app.media.loading") placeholderSrc:$r("app.media.loading")
}),syncLoad:true },syncLoad:true
}) })
}else { }else {
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption:new ImageKnifeOption({ imageKnifeOption:{
loadSrc:$r("app.media.pngSample"), loadSrc:$r("app.media.pngSample"),
placeholderSrc:$r("app.media.loading") placeholderSrc:$r("app.media.loading")
}),syncLoad:true },syncLoad:true
}) })
} }
} }
} }
@Entry @Entry
@ComponentV2 @Component
struct ImageTestPage { struct ImageTestPage {
count : number = 0 count : number = 0
rCount: number = 0 rCount: number = 0
scroller: Scroller = new Scroller() scroller: Scroller = new Scroller()
@Local list: MsgModel[] = [] @State list: MsgModel[] = []
@Local imageSize: number =100 @State imageSize: number =100
handAdd(){ handAdd(){
this.count++ this.count++
const msgItem = new MsgModel('add_id'+this.count, 'addBody'+this.count,'cId'+ this.count) const msgItem = new MsgModel('add_id'+this.count, 'addBody'+this.count,'cId'+ this.count)

View File

@ -15,15 +15,15 @@
import { ImageKnifeComponent, ImageKnife, ImageKnifeOption, CacheStrategy } from '@ohos/libraryimageknife' import { ImageKnifeComponent, ImageKnife, ImageKnifeOption, CacheStrategy } from '@ohos/libraryimageknife'
@Entry @Entry
@ComponentV2 @Component
struct TestIsUrlExist { struct TestIsUrlExist {
@Local imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption: ImageKnifeOption = {
loadSrc: $r('app.media.startIcon'), loadSrc: $r('app.media.startIcon'),
placeholderSrc: $r('app.media.loading'), placeholderSrc: $r('app.media.loading'),
errorholderSrc:$r('app.media.failed') errorholderSrc:$r('app.media.failed')
}) }
@Local source: PixelMap | string | Resource = $r("app.media.startIcon") @State source: PixelMap | string | Resource = $r("app.media.startIcon")
@Local source1: PixelMap | string | Resource = $r("app.media.startIcon") @State source1: PixelMap | string | Resource = $r("app.media.startIcon")
build() { build() {
Column() { Column() {

View File

@ -15,19 +15,19 @@
import { ImageKnifeComponent,ImageKnife,ImageKnifeOption } from '@ohos/libraryimageknife' import { ImageKnifeComponent,ImageKnife,ImageKnifeOption } from '@ohos/libraryimageknife'
@Entry @Entry
@ComponentV2 @Component
struct TestPrefetchToFileCachePage { struct TestPrefetchToFileCachePage {
@Local imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption: ImageKnifeOption = {
loadSrc:$r('app.media.startIcon'), loadSrc:$r('app.media.startIcon'),
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed') errorholderSrc:$r('app.media.failed')
}) }
async preload(url:string) { async preload(url:string) {
let fileCachePath = await ImageKnife.getInstance().preLoadCache(url) let fileCachePath = await ImageKnife.getInstance().preLoadCache(url)
console.log("preload-fileCachePath=="+ fileCachePath) console.log("preload-fileCachePath=="+ fileCachePath)
} }
async preload1(url:string) { async preload1(url:string) {
let fileCachePath = await ImageKnife.getInstance().preLoadCache(new ImageKnifeOption({ loadSrc: url })) let fileCachePath = await ImageKnife.getInstance().preLoadCache({ loadSrc: url })
console.log("preload-fileCachePath1=="+ fileCachePath) console.log("preload-fileCachePath1=="+ fileCachePath)
} }
build() { build() {

View File

@ -15,16 +15,16 @@
import { ImageKnifeComponent, ImageKnife, ImageKnifeOption, CacheStrategy } from '@ohos/libraryimageknife' import { ImageKnifeComponent, ImageKnife, ImageKnifeOption, CacheStrategy } from '@ohos/libraryimageknife'
@Entry @Entry
@ComponentV2 @Component
struct TestRemoveCache { struct TestRemoveCache {
@Local imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption: ImageKnifeOption = {
loadSrc: $r('app.media.startIcon'), loadSrc: $r('app.media.startIcon'),
placeholderSrc: $r('app.media.loading'), placeholderSrc: $r('app.media.loading'),
errorholderSrc:$r('app.media.failed') errorholderSrc:$r('app.media.failed')
}) }
@Local source: PixelMap | string | Resource = $r("app.media.startIcon"); @State source: PixelMap | string | Resource = $r("app.media.startIcon");
@Local source1: PixelMap | string | Resource = $r("app.media.startIcon"); @State source1: PixelMap | string | Resource = $r("app.media.startIcon");
@Local url: string = ''; @State url: string = '';
build() { build() {
Column() { Column() {

View File

@ -15,17 +15,12 @@
import { ImageKnifeComponent, ImageKnife, ImageKnifeOption } from '@ohos/libraryimageknife' import { ImageKnifeComponent, ImageKnife, ImageKnifeOption } from '@ohos/libraryimageknife'
@Entry @Entry
@ComponentV2 @Component
struct TestSetCustomImagePage { struct TestSetCustomImagePage {
@State imageKnifeOption: ImageKnifeOption = {
getResourceString(res:Resource){
return getContext().resourceManager.getStringSync(res.id)
}
@Local imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({
loadSrc: $r('app.media.startIcon'), loadSrc: $r('app.media.startIcon'),
placeholderSrc: $r('app.media.loading') placeholderSrc: $r('app.media.loading')
}) }
aboutToAppear(): void { aboutToAppear(): void {
ImageKnife.getInstance().setCustomGetImage(custom) ImageKnife.getInstance().setCustomGetImage(custom)
} }
@ -34,23 +29,23 @@ struct TestSetCustomImagePage {
} }
build() { build() {
Column() { Column() {
Button(this.getResourceString($r('app.string.Custom_network_download')) + " a").onClick(()=>{ Button("自定义下载a").onClick(()=>{
this.imageKnifeOption = new ImageKnifeOption({ this.imageKnifeOption = {
loadSrc: "aaa", loadSrc: "aaa",
placeholderSrc: $r('app.media.loading') placeholderSrc: $r('app.media.loading')
}) }
}) })
Button(this.getResourceString($r('app.string.Custom_network_download')) + " b").onClick(()=>{ Button("自定义下载b").onClick(()=>{
this.imageKnifeOption = new ImageKnifeOption({ this.imageKnifeOption = {
loadSrc: "bbb", loadSrc: "bbb",
placeholderSrc: $r('app.media.loading') placeholderSrc: $r('app.media.loading')
}) }
}) })
Button(this.getResourceString($r('app.string.Custom_network_download')) + " c").onClick(()=>{ Button("自定义下载c").onClick(()=>{
this.imageKnifeOption = new ImageKnifeOption({ this.imageKnifeOption = {
loadSrc: "ccc", loadSrc: "ccc",
placeholderSrc: $r('app.media.loading') placeholderSrc: $r('app.media.loading')
}) }
}) })
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption imageKnifeOption: this.imageKnifeOption

View File

@ -24,12 +24,12 @@ export struct ZuImage {
if (this.src) { if (this.src) {
//当前版本存在bug //当前版本存在bug
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: new ImageKnifeOption({ imageKnifeOption: {
loadSrc: this.src, loadSrc: this.src,
placeholderSrc: this.placeholderSrc, placeholderSrc: this.placeholderSrc,
errorholderSrc: this.errorholderSrc ?? this.placeholderSrc, errorholderSrc: this.errorholderSrc ?? this.placeholderSrc,
objectFit: ImageFit.Cover objectFit: ImageFit.Cover
}) }
}) })
} else { } else {
Image(this.placeholderSrc) Image(this.placeholderSrc)

View File

@ -15,55 +15,55 @@
import { ImageKnifeComponent,CacheStrategy,ImageKnifeOption } from '@ohos/libraryimageknife' import { ImageKnifeComponent,CacheStrategy,ImageKnifeOption } from '@ohos/libraryimageknife'
@Entry @Entry
@ComponentV2 @Component
struct TestWriteCacheStage { struct TestWriteCacheStage {
@Local imageKnifeOption1: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption1: ImageKnifeOption = {
loadSrc:$r('app.media.startIcon'), loadSrc:$r('app.media.startIcon'),
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed') errorholderSrc:$r('app.media.failed')
}) }
@Local imageKnifeOption2: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption2: ImageKnifeOption = {
loadSrc:$r('app.media.startIcon'), loadSrc:$r('app.media.startIcon'),
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed') errorholderSrc:$r('app.media.failed')
}) }
@Local imageKnifeOption3: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption3: ImageKnifeOption = {
loadSrc:$r('app.media.startIcon'), loadSrc:$r('app.media.startIcon'),
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed') errorholderSrc:$r('app.media.failed')
}) }
build() { build() {
Column() { Column() {
Button($r('app.string.Write_memory_and_file')).margin({top:10}).onClick(async ()=>{ Button("写入内存文件缓存").margin({top:10}).onClick(async ()=>{
this.imageKnifeOption1 = new ImageKnifeOption({ this.imageKnifeOption1 = {
loadSrc:'https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp', loadSrc:'https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp',
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed'), errorholderSrc:$r('app.media.failed'),
writeCacheStrategy:CacheStrategy.Default writeCacheStrategy:CacheStrategy.Default
}) }
}) })
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption1 imageKnifeOption: this.imageKnifeOption1
}).width(200).height(200).margin({top:10}) }).width(200).height(200).margin({top:10})
Button($r('app.string.Write_memory')).margin({top:10}).onClick(async ()=>{ Button("写入内存缓存").margin({top:10}).onClick(async ()=>{
this.imageKnifeOption2 = new ImageKnifeOption({ this.imageKnifeOption2 = {
loadSrc:"https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB", loadSrc:"https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB",
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed'), errorholderSrc:$r('app.media.failed'),
writeCacheStrategy:CacheStrategy.Memory writeCacheStrategy:CacheStrategy.Memory
}) }
}) })
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption2 imageKnifeOption: this.imageKnifeOption2
}).width(200).height(200).margin({top:10}) }).width(200).height(200).margin({top:10})
Button($r('app.string.Write_file')).margin({top:10}).onClick(async ()=>{ Button("写入文件缓存").margin({top:10}).onClick(async ()=>{
this.imageKnifeOption3 = new ImageKnifeOption({ this.imageKnifeOption3 = {
loadSrc:'https://img-blog.csdn.net/20140514114029140', loadSrc:'https://img-blog.csdn.net/20140514114029140',
placeholderSrc:$r('app.media.loading'), placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed'), errorholderSrc:$r('app.media.failed'),
writeCacheStrategy:CacheStrategy.File writeCacheStrategy:CacheStrategy.File
}) }
}) })
ImageKnifeComponent({ ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption3 imageKnifeOption: this.imageKnifeOption3

View File

@ -17,17 +17,17 @@ import matrix4 from '@ohos.matrix4'
@Entry @Entry
@ComponentV2 @Component
struct TransformPage { struct TransformPage {
private custom_scale:number = 1 private custom_scale:number = 1
@Local matrix1:object = matrix4.identity().scale({ x: 1, y: 1 }) @State matrix1:object = matrix4.identity().scale({ x: 1, y: 1 })
@Local ImageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ @State ImageKnifeOption: ImageKnifeOption = {
loadSrc: $r("app.media.rabbit"), loadSrc: $r("app.media.rabbit"),
placeholderSrc: $r("app.media.loading"), placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"), errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Contain, objectFit: ImageFit.Contain,
border: { radius: 50 } border: { radius: 50 }
}) }
build() { build() {
Column() { Column() {

View File

@ -15,50 +15,24 @@
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/libraryimageknife' import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/libraryimageknife'
// const logger = new imUtils.logger.IMLogger('Avatar') // const logger = new imUtils.logger.IMLogger('Avatar')
@ObservedV2
export class MyStorage { class MyImageOption extends ImageKnifeOption {
static instance:MyStorage | undefined = undefined account?: string
static getInstance(){
if(MyStorage.instance == undefined) {
MyStorage.instance = new MyStorage()
}
return MyStorage.instance
}
@Trace WeLink_Mob_fontSize_multiple: number = 1
} }
@ComponentV2 @Component
export struct UserAvatar { export struct UserAvatar {
@Prop @Watch('userInfoUpdate') userInfo: string = ""
// @Prop userInfo: string = "" // @Prop userInfo: string = ""
imgSize: number = 100 imgSize: number = 100
radius: number = 12 radius: number = 12
borderSize: number = 0 borderSize: number = 0
imgSizes: number = 1 imgSizes: number = 1
@Local ImageKnifeOption: ImageKnifeOption = new ImageKnifeOption() @State ImageKnifeOption: ImageKnifeOption = new ImageKnifeOption()
@StorageProp('WeLink_Mob_fontSize_multiple') @Watch('updateImgSize') WeLink_Mob_fontSize_multiple: number = 0
scalable: boolean = true; scalable: boolean = true;
@Local calcImgSize: number = 100 @State calcImgSize: number = 100
@Param userInfo: string = ""
@Monitor('userInfo')
userInfoUpdate() {
// if (uri === 'userInfo' && this.imageKnifeOption.account !== this.userInfo.contactId) return;
// // logger.info(`userInfoUpdate uri=${uri} oldAcc=${this.imageKnifeOption.loadSrc} nowAcc=${this.userInfo.externalHeadUrl}`)
// if (this.userInfo.externalHeadUrl === this.imageKnifeOption.loadSrc && this.userInfo.infoUpdateTime.getTime()
// .toString() === this.imageKnifeOption?.signature?.getKey()) return;
this.ImageKnifeOption = new ImageKnifeOption({
//TODO:写死loadSRC场景变更组件大小所有图片不显示
loadSrc: this.userInfo,
placeholderSrc: $r('app.media.loading'),
errorholderSrc: $r('app.media.failed'),
border: { radius:20,width:5,color:$r('app.color.start_window_background') },
objectFit:ImageFit.Contain
// signature: new ObjectKey(this.userInfo.infoUpdateTime.getTime().toString())
})
}
@Local storage: MyStorage = MyStorage.getInstance()
@Monitor('storage.WeLink_Mob_fontSize_multiple')
updateImgSize() {
this.setImageSize()
}
aboutToAppear(): void { aboutToAppear(): void {
this.userInfoUpdate() this.userInfoUpdate()
this.setImageSize() this.setImageSize()
@ -67,19 +41,39 @@ export struct UserAvatar {
setImageSize() { setImageSize() {
if (!this.scalable) { if (!this.scalable) {
this.calcImgSize = this.imgSize this.calcImgSize = this.imgSize
} else if (this.storage.WeLink_Mob_fontSize_multiple < 0.9) { } else if (this.WeLink_Mob_fontSize_multiple < 0.9) {
this.calcImgSize = this.imgSize * 0.9 this.calcImgSize = this.imgSize * 0.9
} else if (this.storage.WeLink_Mob_fontSize_multiple > 1.6) { } else if (this.WeLink_Mob_fontSize_multiple > 1.6) {
this.calcImgSize = this.imgSize * 1.6 this.calcImgSize = this.imgSize * 1.6
} else { } else {
this.calcImgSize = this.imgSize * this.storage.WeLink_Mob_fontSize_multiple this.calcImgSize = this.imgSize * this.WeLink_Mob_fontSize_multiple
} }
} }
updateImgSize() {
this.setImageSize()
}
aboutToReuse(param: ESObject) { aboutToReuse(param: ESObject) {
this.userInfoUpdate() this.userInfoUpdate()
} }
userInfoUpdate() {
// if (uri === 'userInfo' && this.imageKnifeOption.account !== this.userInfo.contactId) return;
// // logger.info(`userInfoUpdate uri=${uri} oldAcc=${this.imageKnifeOption.loadSrc} nowAcc=${this.userInfo.externalHeadUrl}`)
// if (this.userInfo.externalHeadUrl === this.imageKnifeOption.loadSrc && this.userInfo.infoUpdateTime.getTime()
// .toString() === this.imageKnifeOption?.signature?.getKey()) return;
this.ImageKnifeOption = {
//TODO:写死loadSRC场景变更组件大小所有图片不显示
loadSrc: this.userInfo,
placeholderSrc: $r('app.media.loading'),
errorholderSrc: $r('app.media.failed'),
border: { radius:20,width:5,color:$r('app.color.start_window_background') },
objectFit:ImageFit.Contain
// signature: new ObjectKey(this.userInfo.infoUpdateTime.getTime().toString())
}
}
build() { build() {
Row() { Row() {
// Image(this.imageKnifeOption.loadSrc) // Image(this.imageKnifeOption.loadSrc)

View File

@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import { MyStorage, UserAvatar } from './User' import { UserAvatar } from './User'
class CommonDataSource <T> implements IDataSource { class CommonDataSource <T> implements IDataSource {
private dataArray: T[] = [] private dataArray: T[] = []
@ -55,9 +55,9 @@ class CommonDataSource <T> implements IDataSource {
} }
} }
@Entry @Entry
@ComponentV2 @Component
struct Index { struct Index {
@Local hotCommendList:CommonDataSource<string> = new CommonDataSource<string>([]) @State hotCommendList:CommonDataSource<string> = new CommonDataSource<string>([])
private data:string[] = [ private data:string[] = [
"http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg", "http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
"http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg", "http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg",
@ -85,42 +85,26 @@ struct Index {
'https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp', 'https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp',
] ]
aboutToAppear(): void { aboutToAppear(): void {
MyStorage.getInstance().WeLink_Mob_fontSize_multiple = 1 this.hotCommendList.addData(this.hotCommendList.totalCount(),this.data)
AppStorage.set("WeLink_Mob_fontSize_multiple",1)
} }
build() { build() {
Column() { Column() {
Button("bigger").onClick(()=>{ Button("bigger").onClick(()=>{
MyStorage.getInstance().WeLink_Mob_fontSize_multiple = 1.6 AppStorage.set("WeLink_Mob_fontSize_multiple",1.6)
}) })
Button("small").onClick(()=>{ Button("small").onClick(()=>{
MyStorage.getInstance().WeLink_Mob_fontSize_multiple = 0.8 AppStorage.set("WeLink_Mob_fontSize_multiple",0.8)
}) })
List(){ List(){
// LazyForEach(this.hotCommendList,(item:string)=>{ LazyForEach(this.hotCommendList,(item:string)=>{
// ListItem(){ ListItem(){
// ReuseImage({ ReuseImage({
// userInfo:item userInfo:item
// }).width("100%").height("100%").backgroundColor(Color.Yellow) }).width("100%").height("100%").backgroundColor(Color.Yellow)
// }.width(200).height(200).margin({bottom:5}) }.width(200).height(200).margin({bottom:5})
// }) })
Repeat(this.data)
.each((repeatItem)=>{
ListItem(){
ReuseImage({
userInfo:repeatItem.item
}).width("100%").height("100%").backgroundColor(Color.Yellow)
}.width(200).height(200).margin({bottom:5}).key("reuse")
})
.key(item => item+"reuse")
.virtualScroll()
.template("1",(repeatItem)=>{
ListItem(){
ReuseImage({
userInfo:repeatItem.item
}).width("100%").height("100%").backgroundColor(Color.Yellow)
}.width(200).height(200).margin({bottom:5}).key("reuse")
})
} }
// .cachedCount(20) // .cachedCount(20)
.width("100%") .width("100%")
@ -131,13 +115,13 @@ struct Index {
} }
// @Reusable @Reusable
@ComponentV2 @Component
struct ReuseImage { struct ReuseImage {
@Param userInfo:string = "" @State userInfo:string = ""
// aboutToReuse(params: ESObject): void { aboutToReuse(params: ESObject): void {
// this.userInfo = params.userInfo this.userInfo = params.userInfo
// } }
build() { build() {
Column(){ Column(){

View File

@ -18,15 +18,15 @@ import { photoAccessHelper } from '@kit.MediaLibraryKit';
@Entry @Entry
@ComponentV2 @Component
struct DataShareUriLoadPage { struct DataShareUriLoadPage {
@Local imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
new ImageKnifeOption({ {
loadSrc: $r('app.media.icon'), loadSrc: $r('app.media.icon'),
placeholderSrc: $r('app.media.loading'), placeholderSrc: $r('app.media.loading'),
errorholderSrc: $r('app.media.failed') errorholderSrc: $r('app.media.failed')
}); };
build() { build() {
@ -43,10 +43,10 @@ struct DataShareUriLoadPage {
let photoViewPicker = new photoAccessHelper.PhotoViewPicker(); let photoViewPicker = new photoAccessHelper.PhotoViewPicker();
let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoViewPicker.select(photoSelectOptions); let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoViewPicker.select(photoSelectOptions);
uris = photoSelectResult.photoUris; uris = photoSelectResult.photoUris;
this.imageKnifeOption1 = new ImageKnifeOption({ this.imageKnifeOption1 = {
loadSrc: uris[0], loadSrc: uris[0],
placeholderSrc:$r('app.media.loading') placeholderSrc:$r('app.media.loading')
}) }
}).margin({ top: 5, left: 3 }) }).margin({ top: 5, left: 3 })
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).width(300).height(300) ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).width(300).height(300)
}.width('100%').backgroundColor(Color.Pink) }.width('100%').backgroundColor(Color.Pink)

View File

@ -70,10 +70,10 @@ export default function DefaultJobQueueTest() {
} }
function makeRequest(src: string, context: common.UIAbilityContext, priority?: taskpool.Priority): ImageKnifeRequest { function makeRequest(src: string, context: common.UIAbilityContext, priority?: taskpool.Priority): ImageKnifeRequest {
let option: ImageKnifeOption = new ImageKnifeOption({ let option: ImageKnifeOption = {
loadSrc: src, loadSrc: src,
priority: priority priority: priority
}) }
return new ImageKnifeRequest( return new ImageKnifeRequest(
option, option,
context, context,

View File

@ -153,9 +153,9 @@ export default function FileLruCacheTest() {
}); });
it('fileCacheEngineKey', 0, () => { it('fileCacheEngineKey', 0, () => {
let engineKey: IEngineKey = new DefaultEngineKey() let engineKey: IEngineKey = new DefaultEngineKey()
let imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ let imageKnifeOption: ImageKnifeOption = {
loadSrc:"abc" loadSrc:"abc"
}) }
let imageKey = engineKey.generateFileKey(imageKnifeOption.loadSrc,"") let imageKey = engineKey.generateFileKey(imageKnifeOption.loadSrc,"")
let imageAnimatorKey = engineKey.generateFileKey(imageKnifeOption.loadSrc,"",true) let imageAnimatorKey = engineKey.generateFileKey(imageKnifeOption.loadSrc,"",true)
expect(imageKey == imageAnimatorKey).assertFalse() expect(imageKey == imageAnimatorKey).assertFalse()

View File

@ -40,10 +40,10 @@ export default function ImageKnifeTest() {
it('removeMemoryCache', 0, async () => { it('removeMemoryCache', 0, async () => {
let a = 'https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp'; let a = 'https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp';
let option: ImageKnifeOption = new ImageKnifeOption({ let option: ImageKnifeOption = {
loadSrc: 'https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp', loadSrc: 'https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp',
signature: '' signature: ''
}) }
let key = ImageKnife.getInstance() let key = ImageKnife.getInstance()
.getEngineKeyImpl() .getEngineKeyImpl()
.generateMemoryKey('https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp', ImageKnifeRequestSource.SRC, option) .generateMemoryKey('https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp', ImageKnifeRequestSource.SRC, option)

View File

@ -122,9 +122,9 @@ export default function MemoryLruCacheTest() {
it('memoryCacheEngineKey', 0, () => { it('memoryCacheEngineKey', 0, () => {
let engineKey: IEngineKey = new DefaultEngineKey() let engineKey: IEngineKey = new DefaultEngineKey()
let imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ let imageKnifeOption: ImageKnifeOption = {
loadSrc:"abc" loadSrc:"abc"
}) }
let imageKey = engineKey.generateMemoryKey(imageKnifeOption.loadSrc,ImageKnifeRequestSource.SRC,imageKnifeOption) let imageKey = engineKey.generateMemoryKey(imageKnifeOption.loadSrc,ImageKnifeRequestSource.SRC,imageKnifeOption)
let imageAnimatorKey = engineKey.generateMemoryKey(imageKnifeOption.loadSrc,ImageKnifeRequestSource.SRC,imageKnifeOption,true) let imageAnimatorKey = engineKey.generateMemoryKey(imageKnifeOption.loadSrc,ImageKnifeRequestSource.SRC,imageKnifeOption,true)
expect(imageKey == imageAnimatorKey).assertFalse() expect(imageKey == imageAnimatorKey).assertFalse()

View File

@ -1,52 +0,0 @@
/*
* 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import { SendableData } from '@ohos/imageknife/src/main/ets/components/imageknife/SendableData'
export default function SendableDataTest() {
describe('SendableDataTest', ()=> {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll( ()=> {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
})
beforeEach( ()=> {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
})
afterEach( ()=> {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
})
afterAll( ()=> {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
})
it('TestPlaceHolderCacheKey', 0, () => {
let value: string = "placeholderRegisterCacheKey";
let data: SendableData = new SendableData();
data.setPlaceHolderRegisterCacheKey(value);
expect(data.getPlaceHolderRegisterCacheKey()).assertEqual(value);
})
it('TestPlaceHolderMemoryCacheKey', 1, () => {
let value: string = "placeholderRegisterMemoryCacheKey";
let data: SendableData = new SendableData();
data.setPlaceHolderRegisterMemoryCacheKey(value);
expect(data.getPlaceHolderRegisterMemoryCacheKey()).assertEqual(value);
})
})
}

View File

@ -1,106 +0,0 @@
/*
* 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import { DownloadClient } from '@ohos/imageknife/src/main/ets/components/imageknife/networkmanage/DownloadClient';
import common from '@ohos.app.ability.common';
import { GlobalContext } from '../testability/GlobalContext';
import { CustomDataFetchClient, DataFetchResult, ImageKnifeGlobal, RequestOption } from '@ohos/imageknife';
const BASE_COUNT: number = 2000;
export default function CustomDataFetchClientTest() {
describe('CustomDataFetchClientTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
})
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
})
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
})
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
})
it('TestIsLocalLoadSrc', 0, () => {
let path = 'invalid path';
let client = new DownloadClient()
expect(client.isLocalLoadSrc(undefined, path)).assertFalse();
let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
if (context != undefined) {
let loadSrc1 = (context as common.UIAbilityContext).filesDir + 'a.jpg';
let loadSrc2 = (context as common.UIAbilityContext).cacheDir + 'b.jpg';
expect(client.isLocalLoadSrc(context, loadSrc1)).assertTrue();
expect(client.isLocalLoadSrc(context, loadSrc2)).assertTrue();
}
})
it('TestLoadData', 1, async () => {
let client = new CustomDataFetchClient();
let request = new RequestOption();
request.loadSrc = $r('app.media.icon');
let error = (await client.loadData(request) as DataFetchResult).error as String;
expect(error).assertEqual('CustomDataFetchClient request or loadSrc error.');
})
it('TestLoadData_customGetImage', 2, async () => {
let client = new CustomDataFetchClient();
let request = new RequestOption();
request.loadSrc = 'http://e.hiphotos.baidu.com/image/pic/item/4e4a20a4462309f7e41f5cfe760e0cf3d6cad6ee.jpg';
request.customGetImage = (context: Context, src: string) => {
// 这里是模拟的customGetImage逻辑
return Promise.resolve(new DataFetchResult());
}
console.log('LXH', 'TestLoadData 2 --1 customGetImage is undefined ?' + (request.customGetImage == undefined));
let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
let result = await client.loadData(request);
if (context != undefined) {
console.log('LXH', 'TestLoadData 2 --2');
expect(typeof result)
.assertEqual(typeof (await request?.customGetImage(context as common.UIAbilityContext, request.loadSrc)));
}
})
it('TestLoadData_combineArrayBuffers', 3, () => {
// 创建几个ArrayBuffer作为测试数据
const arrayBuffer1 = new ArrayBuffer(4);
const uint8Array1 = new Uint8Array(arrayBuffer1);
uint8Array1[0] = 1;
uint8Array1[1] = 2;
uint8Array1[2] = 3;
uint8Array1[3] = 4;
const arrayBuffer2 = new ArrayBuffer(2);
const uint8Array2 = new Uint8Array(arrayBuffer2);
uint8Array2[0] = 5;
uint8Array2[1] = 6;
let client = new CustomDataFetchClient();
const combinedArrayBuffer = client.combineArrayBuffers([arrayBuffer1, arrayBuffer2]);
expect(combinedArrayBuffer.byteLength).assertEqual(6);
const combinedUint8Array = new Uint8Array(combinedArrayBuffer);
for (let i = 0; i < 4; i++) {
expect(combinedUint8Array[i]).assertEqual(uint8Array1[i]);
}
for (let i = 0; i < 2; i++) {
expect(combinedUint8Array[i + 4]).assertEqual(uint8Array2[i]);
}
});
})
}

View File

@ -44,7 +44,7 @@ export default function ImageKnifeOptionTest() {
imageWidth: 0, imageWidth: 0,
imageHeight: 0, imageHeight: 0,
} }
let imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ let imageKnifeOption: ImageKnifeOption = {
loadSrc: $r("app.media.rabbit"), loadSrc: $r("app.media.rabbit"),
onLoadListener: { onLoadListener: {
onLoadFailed: (err) => { onLoadFailed: (err) => {
@ -58,7 +58,7 @@ export default function ImageKnifeOptionTest() {
return data; return data;
}, },
}, },
}) }
if (imageKnifeOption.onLoadListener && imageKnifeOption.onLoadListener.onLoadSuccess && imageKnifeOption.onLoadListener.onLoadFailed) { if (imageKnifeOption.onLoadListener && imageKnifeOption.onLoadListener.onLoadSuccess && imageKnifeOption.onLoadListener.onLoadFailed) {
imageKnifeOption.onLoadListener.onLoadSuccess(a,imageData); imageKnifeOption.onLoadListener.onLoadSuccess(a,imageData);
imageKnifeOption.onLoadListener.onLoadFailed(a); imageKnifeOption.onLoadListener.onLoadFailed(a);

View File

@ -14,7 +14,7 @@
"main": "index.ets", "main": "index.ets",
"repository": "https://gitee.com/openharmony-tpc/ImageKnife", "repository": "https://gitee.com/openharmony-tpc/ImageKnife",
"type": "module", "type": "module",
"version": "3.0.2-rc.1", "version": "3.0.2",
"dependencies": { "dependencies": {
"@ohos/gpu_transform": "^1.0.2" "@ohos/gpu_transform": "^1.0.2"
}, },

View File

@ -191,10 +191,10 @@ export class ImageKnife {
*/ */
getCacheImage(loadSrc: string, getCacheImage(loadSrc: string,
cacheType: CacheStrategy = CacheStrategy.Default, signature?: string): Promise<ImageKnifeData | undefined> { cacheType: CacheStrategy = CacheStrategy.Default, signature?: string): Promise<ImageKnifeData | undefined> {
let option: ImageKnifeOption = new ImageKnifeOption({ let option: ImageKnifeOption = {
loadSrc: loadSrc, loadSrc: loadSrc,
signature:signature signature:signature
}) }
let engineKeyImpl: IEngineKey = this.getEngineKeyImpl(); let engineKeyImpl: IEngineKey = this.getEngineKeyImpl();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -218,7 +218,7 @@ export class ImageKnife {
*/ */
putCacheImage(url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string) { putCacheImage(url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string) {
let memoryKey = this.getEngineKeyImpl() let memoryKey = this.getEngineKeyImpl()
.generateMemoryKey(url, ImageKnifeRequestSource.SRC, new ImageKnifeOption({ loadSrc: url, signature: signature })); .generateMemoryKey(url, ImageKnifeRequestSource.SRC, { loadSrc: url, signature: signature });
let fileKey = this.getEngineKeyImpl().generateFileKey(url, signature); let fileKey = this.getEngineKeyImpl().generateFileKey(url, signature);
let imageKnifeData: ImageKnifeData = { source: pixelMap, imageWidth: 0, imageHeight: 0 }; let imageKnifeData: ImageKnifeData = { source: pixelMap, imageWidth: 0, imageHeight: 0 };
switch (cacheType) { switch (cacheType) {
@ -252,9 +252,9 @@ export class ImageKnife {
if (url instanceof ImageKnifeOption) { if (url instanceof ImageKnifeOption) {
imageKnifeOption = url; imageKnifeOption = url;
} else { } else {
imageKnifeOption = new ImageKnifeOption({ imageKnifeOption = {
loadSrc: url loadSrc: url
}); };
} }
let key = this.getEngineKeyImpl().generateFileKey(imageKnifeOption.loadSrc, imageKnifeOption.signature); let key = this.getEngineKeyImpl().generateFileKey(imageKnifeOption.loadSrc, imageKnifeOption.signature);
if (this.fileCache !== undefined) { if (this.fileCache !== undefined) {

View File

@ -19,14 +19,15 @@ import { ImageKnife } from '../ImageKnife';
import { LogUtil } from '../utils/LogUtil'; import { LogUtil } from '../utils/LogUtil';
import { ImageKnifeRequestSource } from '../model/ImageKnifeData'; import { ImageKnifeRequestSource } from '../model/ImageKnifeData';
@ComponentV2 @Component
export struct ImageKnifeAnimatorComponent { export struct ImageKnifeAnimatorComponent {
@Param animatorOption: AnimatorOption = new AnimatorOption(); @Watch('watchImageKnifeOption') @ObjectLink imageKnifeOption: ImageKnifeOption;
@Local pixelMap: PixelMap | string | undefined = undefined @State animatorOption: AnimatorOption = new AnimatorOption();
@Local imageAnimator: Array<ImageFrameInfo> | undefined = undefined @State pixelMap: PixelMap | string | undefined = undefined
@Local adaptiveWidth: Length = '100%' @State imageAnimator: Array<ImageFrameInfo> | undefined = undefined
@Local adaptiveHeight: Length = '100%' @State adaptiveWidth: Length = '100%'
@Local objectFit: ImageFit = ImageFit.Contain @State adaptiveHeight: Length = '100%'
@State objectFit: ImageFit = ImageFit.Contain
private request: ImageKnifeRequest | undefined private request: ImageKnifeRequest | undefined
private lastWidth: number = 0 private lastWidth: number = 0
private lastHeight: number = 0 private lastHeight: number = 0
@ -34,17 +35,7 @@ export struct ImageKnifeAnimatorComponent {
private currentHeight: number = 0 private currentHeight: number = 0
private componentVersion: number = 0 private componentVersion: number = 0
private currentContext: common.UIAbilityContext | undefined = undefined private currentContext: common.UIAbilityContext | undefined = undefined
@Param imageKnifeOption: ImageKnifeOption = new ImageKnifeOption();
@Monitor('imageKnifeOption',
"imageKnifeOption.loadSrc","imageKnifeOption.signature","imageKnifeOption.transformation","imageKnifeOption.border","imageKnifeOption.objectFit")
watchImageKnifeOption() {
if (this.request !== undefined) {
this.request.requestState = ImageKnifeRequestState.DESTROY
}
this.request = undefined
this.componentVersion++
ImageKnife.getInstance().execute(this.getRequest(this.currentWidth, this.currentHeight))
}
aboutToAppear(): void { aboutToAppear(): void {
this.objectFit = this.imageKnifeOption.objectFit === undefined ? ImageFit.Contain : this.imageKnifeOption.objectFit this.objectFit = this.imageKnifeOption.objectFit === undefined ? ImageFit.Contain : this.imageKnifeOption.objectFit
} }
@ -95,6 +86,15 @@ export struct ImageKnifeAnimatorComponent {
.onRepeat(this.animatorOption.onRepeat) .onRepeat(this.animatorOption.onRepeat)
} }
watchImageKnifeOption() {
if (this.request !== undefined) {
this.request.requestState = ImageKnifeRequestState.DESTROY
}
this.request = undefined
this.componentVersion++
ImageKnife.getInstance().execute(this.getRequest(this.currentWidth, this.currentHeight),true)
}
getCurrentContext(): common.UIAbilityContext { getCurrentContext(): common.UIAbilityContext {
if (this.currentContext == undefined) { if (this.currentContext == undefined) {
this.currentContext = getContext(this) as common.UIAbilityContext this.currentContext = getContext(this) as common.UIAbilityContext

View File

@ -21,13 +21,14 @@ import { ImageKnifeData, ImageKnifeRequestSource } from '../model/ImageKnifeData
import { IEngineKey } from '../key/IEngineKey'; import { IEngineKey } from '../key/IEngineKey';
import { DefaultEngineKey } from '../key/DefaultEngineKey'; import { DefaultEngineKey } from '../key/DefaultEngineKey';
@ComponentV2 @Component
export struct ImageKnifeComponent { export struct ImageKnifeComponent {
@Local pixelMap: PixelMap | string | undefined = undefined @Watch('watchImageKnifeOption') @ObjectLink imageKnifeOption: ImageKnifeOption;
@Param syncLoad: boolean = false @State pixelMap: PixelMap | string | undefined = undefined
@Local adaptiveWidth: Length = '100%' @State syncLoad: boolean = false
@Local adaptiveHeight: Length = '100%' @State adaptiveWidth: Length = '100%'
@Local objectFit: ImageFit = ImageFit.Contain @State adaptiveHeight: Length = '100%'
@State objectFit: ImageFit = ImageFit.Contain
private request: ImageKnifeRequest | undefined private request: ImageKnifeRequest | undefined
private lastWidth: number = 0 private lastWidth: number = 0
private lastHeight: number = 0 private lastHeight: number = 0
@ -35,20 +36,6 @@ export struct ImageKnifeComponent {
private currentHeight: number = 0 private currentHeight: number = 0
private componentVersion: number = 0 private componentVersion: number = 0
private currentContext: common.UIAbilityContext | undefined = undefined private currentContext: common.UIAbilityContext | undefined = undefined
@Param imageKnifeOption: ImageKnifeOption = new ImageKnifeOption();
@Monitor('imageKnifeOption',
"imageKnifeOption.loadSrc","imageKnifeOption.signature","imageKnifeOption.transformation","imageKnifeOption.border","imageKnifeOption.objectFit")
watchImageKnifeOption() {
this.clearLastRequest()
this.componentVersion++
this.objectFit = this.imageKnifeOption.objectFit === undefined ? ImageFit.Contain : this.imageKnifeOption.objectFit
LogUtil.log("watchImageKnifeOption execute request:width=" + this.currentWidth + " height= " + this.currentHeight
+ " loadSrc = " + this.request?.imageKnifeOption.loadSrc
+ " placeholderSrc = " + this.request?.imageKnifeOption.placeholderSrc
+ " errorholderSrc = " + this.request?.imageKnifeOption.errorholderSrc)
ImageKnife.getInstance().execute(this.getRequest(this.currentWidth, this.currentHeight))
}
aboutToAppear(): void { aboutToAppear(): void {
this.objectFit = this.imageKnifeOption.objectFit === undefined ? ImageFit.Contain : this.imageKnifeOption.objectFit this.objectFit = this.imageKnifeOption.objectFit === undefined ? ImageFit.Contain : this.imageKnifeOption.objectFit
@ -83,7 +70,6 @@ export struct ImageKnifeComponent {
aboutToRecycle() { aboutToRecycle() {
this.clearLastRequest() this.clearLastRequest()
} }
/** /**
* 对已DESTROY的组件不再发起请求 * 对已DESTROY的组件不再发起请求
*/ */
@ -93,7 +79,6 @@ export struct ImageKnifeComponent {
this.request = undefined this.request = undefined
} }
} }
build() { build() {
Image(this.pixelMap) Image(this.pixelMap)
.colorFilter(this.imageKnifeOption.drawingColorFilter) .colorFilter(this.imageKnifeOption.drawingColorFilter)
@ -109,19 +94,29 @@ export struct ImageKnifeComponent {
this.currentHeight = newValue.height as number this.currentHeight = newValue.height as number
this.lastWidth = oldValue.width as number this.lastWidth = oldValue.width as number
this.lastHeight = oldValue.height as number this.lastHeight = oldValue.height as number
if (this.currentWidth <= 0 || this.currentHeight <= 0) {
// 条件1: 宽高值均有效,值>0. 条件2当前宽高与上一次宽高不同 // 存在宽或者高为0,此次重回无意义,无需进行request请求
if (this.currentWidth > 0 && this.currentHeight > 0 && } else {
(this.currentHeight != this.lastHeight || this.currentWidth != this.lastWidth)) { // 前提:宽高值均有效,值>0. 条件1当前宽高与上一次宽高不同 条件2:当前是第一次绘制
LogUtil.log("onSizeChange execute request:width=" + this.currentWidth + " height= " + this.currentHeight if (this.currentHeight != this.lastHeight || this.currentWidth != this.lastWidth) {
+ " loadSrc = " + this.request?.imageKnifeOption.loadSrc LogUtil.log("execute request:width=" + this.currentWidth + " height= " + this.currentHeight)
+ " placeholderSrc = " + this.request?.imageKnifeOption.placeholderSrc ImageKnife.getInstance().execute(this.getRequest(this.currentWidth, this.currentHeight))
+ " errorholderSrc = " + this.request?.imageKnifeOption.errorholderSrc) }
ImageKnife.getInstance().execute(this.getRequest(this.currentWidth, this.currentHeight))
} }
}) })
} }
watchImageKnifeOption() {
this.clearLastRequest()
this.componentVersion++
this.objectFit = this.imageKnifeOption.objectFit === undefined ? ImageFit.Contain : this.imageKnifeOption.objectFit
LogUtil.log("watchImageKnifeOption execute request:width=" + this.currentWidth + " height= " + this.currentHeight
+ " loadSrc = " + this.request?.imageKnifeOption.loadSrc
+ " placeholderSrc = " + this.request?.imageKnifeOption.placeholderSrc
+ " errorholderSrc = " + this.request?.imageKnifeOption.errorholderSrc)
ImageKnife.getInstance().execute(this.getRequest(this.currentWidth, this.currentHeight))
}
getCurrentContext(): common.UIAbilityContext { getCurrentContext(): common.UIAbilityContext {
if (this.currentContext == undefined) { if (this.currentContext == undefined) {
this.currentContext = getContext(this) as common.UIAbilityContext this.currentContext = getContext(this) as common.UIAbilityContext
@ -143,10 +138,24 @@ export struct ImageKnifeComponent {
return //针对reuse场景不显示历史图片 return //针对reuse场景不显示历史图片
} }
this.pixelMap = pixelMap this.pixelMap = pixelMap
if (typeof this.pixelMap !== 'string' && this.imageKnifeOption.objectFit === ImageFit.Auto) { //针对静态图高度自适应 if (typeof this.pixelMap !== 'string') {
let info = await this.pixelMap.getImageInfo() if (this.imageKnifeOption.objectFit === ImageFit.Auto) {
this.adaptiveWidth = this.currentWidth let info = await this.pixelMap.getImageInfo()
this.adaptiveHeight = info.size.height * this.currentWidth / info.size.width
this.adaptiveWidth = this.currentWidth
this.adaptiveHeight = info.size.height * this.currentWidth / info.size.width
// if (this.currentWidth / this.currentHeight > info.size.width / info.size.height) {
// this.adaptiveWidth = this.currentWidth
// this.adaptiveHeight = info.size.height * this.currentWidth / this.currentHeight
// }
// else {
// this.adaptiveWidth = info.size.width * this.currentWidth / this.currentHeight
// this.adaptiveHeight = this.currentHeight
// }
}
} else {
//console.info("KKKKKKKKKKK:" + pixelMap)
} }
if (requestSource == ImageKnifeRequestSource.SRC) { if (requestSource == ImageKnifeRequestSource.SRC) {
@ -165,4 +174,8 @@ export struct ImageKnifeComponent {
return this.request return this.request
} }
}
interface KeyCanvas {
keyId: string
} }

View File

@ -22,55 +22,38 @@ export interface HeaderOptions {
key: string; key: string;
value: Object; value: Object;
} }
interface AnimatorType {
state?: AnimationStatus @Observed
iterations?: number
reverse?: boolean
onStart?:()=>void
onFinish?:()=>void
onPause?:()=>void
onCancel?:()=>void
onRepeat?:()=>void
}
@ObservedV2
export class AnimatorOption { export class AnimatorOption {
@Trace @Track
state?: AnimationStatus = AnimationStatus.Running state?: AnimationStatus = AnimationStatus.Running
@Trace @Track
iterations?: number = -1 iterations?: number = -1
@Trace @Track
reverse?: boolean = false reverse?: boolean = false
@Trace @Track
onStart?:()=>void onStart?:()=>void
@Trace @Track
onFinish?:()=>void onFinish?:()=>void
@Trace @Track
onPause?:()=>void onPause?:()=>void
@Trace @Track
onCancel?:()=>void onCancel?:()=>void
@Trace @Track
onRepeat?:()=>void onRepeat?:()=>void
constructor(option?:AnimatorType) {
this.state = option?.state
this.iterations = option?.iterations
this.reverse = option?.reverse
this.onStart = option?.onStart
this.onFinish = option?.onFinish
this.onPause = option?.onPause
this.onCancel = option?.onCancel
this.onRepeat = option?.onRepeat
}
} }
interface ImageOption {
@Observed
export class ImageKnifeOption {
// 主图资源 // 主图资源
loadSrc: string | PixelMap | Resource loadSrc: string | PixelMap | Resource = "";
// 占位图 // 占位图
placeholderSrc?: string | PixelMap | Resource placeholderSrc?: string | PixelMap | Resource;
// 失败占位图 // 失败占位图
errorholderSrc?: string | PixelMap | Resource errorholderSrc?: string | PixelMap | Resource;
headerOption?: Array<HeaderOptions>; headerOption?: Array<HeaderOptions>;
// 自定义缓存关键字 // 自定义缓存关键字
signature?: string signature?: string;
// 主图填充效果 // 主图填充效果
objectFit?: ImageFit objectFit?: ImageFit
// 占位图填充效果 // 占位图填充效果
@ -82,65 +65,16 @@ interface ImageOption {
// 缓存策略 // 缓存策略
writeCacheStrategy?: CacheStrategy writeCacheStrategy?: CacheStrategy
// 仅使用缓存加载数据 // 仅使用缓存加载数据
onlyRetrieveFromCache?: boolean; onlyRetrieveFromCache?: boolean = false;
priority?: taskpool.Priority priority?: taskpool.Priority = taskpool.Priority.LOW
context?: common.UIAbilityContext; context?: common.UIAbilityContext;
progressListener?: (progress: number) => void; progressListener?: (progress: number) => void;
transformation?: PixelMapTransformation transformation?: PixelMapTransformation
onLoadListener?: OnLoadCallBack | undefined; onLoadListener?: OnLoadCallBack | undefined;
onComplete?:(event:EventImage | undefined) => void onComplete?:(event:EventImage | undefined) => void
drawingColorFilter?: ColorFilter | drawing.ColorFilter drawingColorFilter?: ColorFilter | drawing.ColorFilter
} constructor() {
@ObservedV2
export class ImageKnifeOption {
// 主图资源
@Trace loadSrc: string | PixelMap | Resource = "";
// 占位图
placeholderSrc?: string | PixelMap | Resource;
// 失败占位图
errorholderSrc?: string | PixelMap | Resource;
headerOption?: Array<HeaderOptions>;
// 自定义缓存关键字
@Trace signature?: string;
// 主图填充效果
@Trace objectFit?: ImageFit
// 占位图填充效果
placeholderObjectFit?: ImageFit
// 错误图填充效果
errorholderObjectFit?: ImageFit
customGetImage?: (context: Context, src: string | PixelMap | Resource) => Promise<ArrayBuffer | undefined>
@Trace border?: BorderOptions
// 缓存策略
writeCacheStrategy?: CacheStrategy
// 仅使用缓存加载数据
onlyRetrieveFromCache?: boolean = false;
priority?: taskpool.Priority = taskpool.Priority.LOW
context?: common.UIAbilityContext;
progressListener?: (progress: number) => void;
@Trace transformation?: PixelMapTransformation
onLoadListener?: OnLoadCallBack | undefined;
onComplete?:(event:EventImage | undefined) => void
drawingColorFilter?: ColorFilter | drawing.ColorFilter
constructor(option?:ImageOption) {
this.loadSrc = option?.loadSrc == undefined ? "" : option?.loadSrc
this.placeholderSrc = option?.placeholderSrc
this.errorholderSrc = option?.errorholderSrc
this.headerOption = option?.headerOption
this.signature = option?.signature
this.objectFit = option?.objectFit
this.placeholderObjectFit = option?.placeholderObjectFit
this.errorholderObjectFit = option?.errorholderObjectFit
this.customGetImage = option?.customGetImage
this.border = option?.border
this.writeCacheStrategy = option?.writeCacheStrategy
this.onlyRetrieveFromCache = option?.onlyRetrieveFromCache
this.priority = option?.priority
this.context = option?.context
this.progressListener = option?.progressListener
this.transformation = option?.transformation
this.onLoadListener = option?.onLoadListener
this.onComplete = option?.onComplete
this.drawingColorFilter = option?.drawingColorFilter
} }
} }

View File

@ -14,11 +14,11 @@
*/ */
import { ImageKnife , ImageKnifeComponent ,ImageKnifeOption } from "@ohos/imageknife" import { ImageKnife , ImageKnifeComponent ,ImageKnifeOption } from "@ohos/imageknife"
@ComponentV2 @Component
export struct IndexComponent { export struct IndexComponent {
@Local imageKnifeOption: ImageKnifeOption = new ImageKnifeOption({ @State imageKnifeOption: ImageKnifeOption = {
loadSrc: $r('app.media.startIcon') loadSrc: $r('app.media.startIcon')
}) }
build() { build() {
Column() { Column() {
Button($r('app.string.Preload')).onClick((event: ClickEvent) => { Button($r('app.string.Preload')).onClick((event: ClickEvent) => {