- 封装SignatureBoard组件
import { image } from '@kit.ImageKit';
@Component
export struct SignatureBoard {
private boardWidth: number = 300
private boardHeight: number = 200
private lastX: number = 0
private lastY: number = 0
private isDown: Boolean = false
private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.All, distance: 1 })
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
onConfirm: (pixelMap: image.PixelMap) => void = () => {
}
draw(startX: number, startY: number, endX: number, endY: number) {
this.context.moveTo(startX, startY);
this.context.lineTo(endX, endY);
this.context.stroke();
}
build() {
Column({ space: 10 }) {
Canvas(this.context)
.width(this.boardWidth)
.height(this.boardHeight)
.backgroundColor('#fff')
.borderRadius(6)
.border({ width: 1, color: Color.Gray })
.onReady(() => {
this.context.lineWidth = 3;
this.context.strokeStyle = "#000";
})
.gesture(
PanGesture(this.panOption)
.onActionStart((event) => {
this.isDown = true;
this.lastX = event.fingerList[0].localX
this.lastY = event.fingerList[0].localY
this.context.beginPath();
})
.onActionUpdate((event) => {
if (!this.isDown) return
const offsetX = event.fingerList[0].localX
const offsetY = event.fingerList[0].localY
this.draw(this.lastX, this.lastY, offsetX, offsetY)
this.lastX = offsetX
this.lastY = offsetY
})
.onActionEnd(() => {
this.isDown = false;
this.context.closePath();
})
)
Row({ space: 10 }) {
Button('重签')
.onClick(() => {
this.context.clearRect(0, 0, this.boardWidth, this.boardHeight)
})
Button('确认')
.onClick(() => {
const img = this.context.getPixelMap(0, 0, this.boardWidth, this.boardHeight)
this.onConfirm(img)
})
}
}
}
}
- 引入SignatureBoard组件
import { image } from '@kit.ImageKit'
import { SignatureBoard } from './components'
@Entry
@Component
struct SignatureBoardPage {
@State img: image.PixelMap | null = null
build() {
Column({ space: 10 }) {
SignatureBoard({
onConfirm: (pixelMap) => {
this.img = pixelMap
}
})
}
.padding({ top: 80 })
.width('100%')
.height('100%')
}
}
- 使用Image组件测试
Image(this.img)
.width(300)
.height(200)
.objectFit(ImageFit.Auto)
.borderRadius(6)
.border({
width: 1,
color: Color.Gray
})
- 效果图