果冻|
HarmonyOS 5
#HarmonyOS最强问答官# 在ArkUI中,如何实现Canvas的滚动和缩放功能?
描述:在开发过程中,有时需要实现Canvas的滚动和缩放功能,以便用户能够更详细地查看或操作图形。请问,在ArkUI中,如何实现这些功能?需要注意哪些细节和性能优化点?
1
浏览192 发布于2024-12-02 13:33中国香港
全部评论
最多点赞
最新发布
最早发布
哈希魔术师缩放demo:
收起
自动换行
深色代码主题
复制
import { image } from '@kit.ImageKit';
import { HashMap } from '@kit.ArkTS';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { resourceManager } from '@kit.LocalizationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { drawing } from '@kit.ArkGraphics2D';
import { componentUtils, window } from '@kit.ArkUI';
const entryContext: Context = getContext(this);
const resourceMgr: resourceManager.ResourceManager = entryContext.resourceManager;
@Preview
@Component
export struct RightCanvas {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
@State canvasWidth: number = 400
@State canvasHeight: number = 200
@State pixelMap: PixelMap | undefined = undefined;
canvasDraw: drawing.Canvas | undefined = undefined;
@State selectImage: string = ''
aboutToAppear(): void {
getContext(this).eventHub.on("loadImage", (imageName: string) => {
this.loadImage(imageName)
})
}
aboutToDisappear(): void {
getContext(this).eventHub.off("loadImage")
}
private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600)
// private staticCanvas:StaticCanvas = new StaticCanvas()
build() {
Column() {
Row() {
Scroll() {
Scroll() {
Canvas(this.context)
.width(this.canvasWidth)
.height(this.canvasHeight)
.border({
width: this.pixelMap != undefined ? 1 : 0,
color: Color.Red
})
.onReady(() => {
})
.onClick((event) => {
console.log(`${event.x},${event.y}`)
})
}
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.On)
}
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.On)
// Text("预览")
// Image(this.pixelMap).width(200).height(200)
}
.layoutWeight(1)
.width('100%')
.justifyContent(FlexAlign.Center)
.alignItems(VerticalAlign.Center)
.id("canvasContainer")
Row({ space: 5 }) {
Image($r('app.media.auto'))
.width(28).height(28)
.onClick(async () => {
let textRange = componentUtils.getRectangleById("canvasContainer")
let width = textRange.size.width
let height = textRange.size.height
console.log(`组件宽${width},组件高${height}`)
if (this.pixelMap == undefined) {
return
}
this.pixelMap.getImageInfo().then((imageInfo) => {
let imageWidth = imageInfo.size.width
let imageHeight = imageInfo.size.height
let zoom = Math.min(width / imageWidth, height / imageHeight)
if (zoom < 1) {
this.context.reset()
this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
this.pixelMap?.scale(zoom, zoom).then(() => {
this.flushPixelMap()
this.canvasWidth = px2vp(imageWidth) * zoom
this.canvasHeight = px2vp(imageHeight) * zoom
console.log(`缩放后的图像宽${this.pixelMap?.getImageInfoSync().size.width},缩放比例${zoom}`)
this.context.drawImage(this.pixelMap, 0, 0)
console.log("缩放完成")
})
}
})
})
}
.justifyContent(FlexAlign.Center)
.backgroundColor('#eaeaea')
.height(45)
.flexGrow(0)
.width('100%')
}
.justifyContent(FlexAlign.SpaceBetween)
.width('100%')
.height('100%')
}
flushPixelMap() {
let temp = this.pixelMap;
this.pixelMap = undefined;
this.pixelMap = temp;
}
loadImage(imageName: string) {
// this.context.reset();
if (hilog.isLoggable(0x001, "canvas", hilog.LogLevel.DEBUG)) {
hilog.debug(0x0001, "canvas", "画布尺寸为(宽:%{public}d,高:%{public}d)", this.context.width, this.context.height)
}
if (hilog.isLoggable(0x001, "canvas", hilog.LogLevel.INFO)) {
hilog.info(0x0001, "canvas", "加载图像,图像名称为[%{public}s]", imageName)
}
let fd = resourceMgr.getRawFdSync(imageName)
let imageSource: image.ImageSource = image.createImageSource(fd);
imageSource.createPixelMap((err: BusinessError, pixelMap: image.PixelMap) => {
if (err) {
hilog.error(0x0001, "canvas", "加载图像失败,错误码[%{public}d],错误信息[%{public}s]", err.code, err.message);
} else {
this.context.reset()
this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
this.pixelMap = pixelMap
this.canvasWidth = px2vp(this.pixelMap.getImageInfoSync().size.width)
this.canvasHeight = px2vp(this.pixelMap.getImageInfoSync().size.height)
this.context.drawImage(this.pixelMap, 0, 0)
}
})
}
}滚动demo:
收起
自动换行
深色代码主题
复制
@Entry
@Component
struct Page9 {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
@State @Watch('draw') positionXY: number[] = [0, 0]; // 原始坐标点
prePosition: number[] = []; // 上一次坐标点
clickXY: number[] = []; // 鼠标落下坐标点
shiftingPosition: number[] = []; // 偏移参照点
rectWidth: number = 100;
rectHeight: number = 100;
PanGestureFlag: boolean = false;
build() {
Column() {
Canvas(this.context)
.width('100%')
.height('50%')
.backgroundColor('#ffff00')
.margin({ top: 50 })
.onReady(() => {
this.draw()
})
.gesture(// 拖拽手势
PanGesture()
.onActionStart((event: GestureEvent) => {
let x = event.fingerList[0].localX;
let y = event.fingerList[0].localY;
if (x >= this.positionXY[0] &&
x <= (this.positionXY[0] + this.rectWidth) &&
y > this.positionXY[1] &&
y <= (this.positionXY[1] + this.rectHeight)
) {
this.PanGestureFlag = true; // 可以拖动
this.clickXY = [parseInt(`${x}`), parseInt(`${y}`)];
this.shiftingPosition = [...this.positionXY];
console.info(`shiftingPosition ${this.shiftingPosition}`)
}
})
.onActionUpdate((event: GestureEvent) => {
if (this.PanGestureFlag) {
this.prePosition = [...this.positionXY]; // 保存上一次坐标
const x = this.shiftingPosition[0] + parseInt(`${event.offsetX}`);
const y = this.shiftingPosition[1] + parseInt(`${event.offsetY}`);
this.positionXY = [x, y];
// console.info(`shiftingPosition ${this.shiftingPosition}`);
console.log(`positionXY ${this.positionXY}`);
}
})
.onActionEnd(() => {
this.PanGestureFlag = false; // 结束后,停止拖动
})
)
}
}
draw() {
this.context.reset();
if (this.prePosition.length) {
this.context.clearRect(this.prePosition[0], this.prePosition[1], this.rectWidth, this.rectHeight);
}
this.context.fillRect(this.positionXY[0], this.positionXY[1], this.rectWidth, this.rectHeight)
}
} 展开全部 
2楼回复于2024-12-03 04:02 来自广东
写回答
所见即所得编辑器, editor1
工具栏 撤消 快捷键 Ctrl+Z 重做 快捷键 Ctrl+Y 格式刷 快捷键 Ctrl+Shift+C 清除格式 加粗 快捷键 Ctrl+B 倾斜 快捷键 Ctrl+I 下划线 快捷键 Ctrl+U 删除线格式调整字号 文本颜色 背景颜色 增加缩进量 减少缩进量 左对齐 居中 右对齐 两端对齐段落间距行间距 项目列表 编号列表 插入水平线 块引用 插入/编辑超链接 快捷键 Ctrl+K 取消超链接 图片 表格 上传附件 导入Word 插入代码 MD编辑器 全屏模式
0/50000
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
- 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
- 如您发布的内容为转载内容,请注明内容来源。
我要提问题
相关推荐
换一批
1
如何解决列表中Canvas加载Lottie动画卡顿的问题
2
HarmonyOS Canvas通过手势缩放Canvas组件之后,会出现放大模糊的现象 (API12+)
3
HarmonyOS 如何实现用Canvas绘制一个圆点(API12+)
4
HarmonyOS 如何用canvas实现刮刮乐效果?(API12+)
5
HarmonyOS 滚动联动,支持ArkTS的scrollView和CAPI的scrollView之间滚动联动吗 (API12+)
6
HarmonyOS 如何实现列表List整体的缩放,且列表能正常滑动滚动?(API12+)
7
HarmonyOS 滚动联动支持ArkTS的scrollView和CAPI的scrollView之间滚动联动吗 (API12+)
8
HarmonyOS 如何实现手势滑动时一组图标联动的滚动动画效果(API12+)
了解社区公约,与您携手共创和谐专业的开发者社区。




































苏公安网备 32011402010933号