# 图像
QML画布(canvas)支持从多个来源绘制图像。 要在画布内使用图像,需要先加载图像。 在下面的示例中,使用Component.onCompleted
处理器加载图像。
译者笔记:loadImage()用于异步加载图像。一旦图像准备后发出.将会发出imageLoaded()信号。加载的图像可以使用unloadImage()方法解除加载。只有加载的图像才能用于画布上绘制。
onPaint: {
var ctx = getContext("2d")
// draw an image
ctx.drawImage('assets/ball.png', 10, 10)
// store current context setup
ctx.save()
ctx.strokeStyle = '#ff2a68'
// create a triangle as clip region
ctx.beginPath()
ctx.moveTo(110,10)
ctx.lineTo(155,10)
ctx.lineTo(135,55)
ctx.closePath()
// translate coordinate system
ctx.clip() // create clip from the path
// draw image with clip applied
ctx.drawImage('assets/ball.png', 100, 10)
// draw stroke around path
ctx.stroke()
// restore previous context
ctx.restore()
}
Component.onCompleted: {
loadImage("assets/ball.png")
}
左侧显示了绘制在左上角10x10位置的球的图像。 右图显示了应用了剪切路径的球。 图像和任何路径都可以使用其他路径进行剪切。 通过定义路径并调用clip()
函数来应用裁剪,接下来所有的绘图操作都将被此路径裁剪。 通过恢复以前的状态或将剪辑区域设置为整个画布,才能再次禁用剪切。