HarmonyOS 鸿蒙Next 无法显示一张png图片
HarmonyOS 鸿蒙Next 无法显示一张png图片
在代码目录下,同时放置一张cs.png的图片,不明白的是,
1.path怎么正确的写?
2.desiredColorSpace要怎么设置,用create(ColorSpace.SRGB)不晓得正不正确?
Canvas(contexts).width(100.percent).height(100.percent).backgroundColor(Color.TRANSPARENT)
.onReady{=>
let path:String="cs.png"
let imgsou:ImageSource=image.createImageSource(path)
let cp=create(ColorSpace.SRGB)
let deo=image.DecodingOptions(sampleSize:1, rotate:0, editable:true, desiredSize:Size(height:300, width:266), desiredRegion:Region(Size(height:300,width:266),0,0), desiredPixelFormat: PixelMapFormat.RGBA_8888, index:0, fitDensity:3, desiredColorSpace:cp)
let px:PixelMap=imgsou.createPixelMap(options:deo)
this.contexts.drawImage(px,0,0)
}
实测发现,CANVAS出现后,闪退,没有出现图片
8 回复
1.path在ets/common/1234.png
demo如下:
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600)
private img:ImageBitmap = new ImageBitmap("common/1234.png")
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() =>{
let offContext = this.offCanvas.getContext("2d", this.settings)
// 使用drawImage接口将图片画在(0,0)为起点,宽高130的区域
offContext.drawImage(this.img,0,0,130,130);
// 使用getImageData接口,获得canvas组件区域中,(50,50)为起点,宽高130范围内的绘制内容
let imagedata = offContext.getImageData(50,50,130,130);
// 使用putImageData接口将得到的ImageData画在起点为(150, 150)的区域中
offContext.putImageData(imagedata,150,150);
// 将离屏绘制的内容画到canvas组件上
let image = this.offCanvas.transferToImageBitmap();
this.context.transferFromImageBitmap(image);
})
}
.width('100%')
.height('100%')
}
}
看懂原理了,非常感谢
找HarmonyOS工作还需要会Flutter的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:https://www.bilibili.com/video/BV1S4411E7LY/?p=17
放rawfile读取
仓颉下,图片放到rawfile里面,大小266*300像素 var huancun:Array<UInt8>=Array<UInt8>(319200,item:0) huancun=resmg.getRawFileContent(“cs.png”)
this.contexts.fillStyle(Color.GREEN)
this.contexts.font(style: FontStyle.Normal, weight: FontWeight.W100, size: 50.vp, family: "sans-serif")
this.contexts.fillText("${huancun.size}", 150, 500)
let colors:Array<UInt8>=Array<UInt8>(319200,item:0)
let opts:InitializationOptions=InitializationOptions(alphaType: AlphaType.OPAQUE, editable: true, pixelFormat: PixelMapFormat.RGBA_8888, scaleMode: ScaleMode.FIT_TARGET_SIZE, size:Size(height: 300, width: 266))
let pm:PixelMap=createPixelMap(colors,opts)
pm.writeBufferToPixels(huancun)
后续,怎么把pm这个pixelmap写到一个canvas中?
arkts里面this.context.drawImage就可以画一个pixelmap,这个canvas和html那个很像的,仓颉还没看过,应该是差不多的
像双缓存一样,一次性转存并显示?