Qt6 QML Book/画布/像素缓冲

Pixel Buffers

像素缓冲

When working with the canvas you are able to retrieve pixel data from the canvas to read or manipulate the pixels of your canvas. To read the image data use createImageData(sw,sh) or getImageData(sx,sy,sw,sh). Both functions return an ImageData object with a widthheight and a data variable. The data variable contains a one-dimensional array of the pixel data retrieved in the RGBA format, where each value varies in the range of 0 to 255. To set pixels on the canvas you can use the putImageData(imagedata, dx, dy) function.

使用画布时,您可以从画布检索像素数据,以读取或操作画布的像素。要读取图像数据,请使用createImageData(sw,sh)或getImageData(sx,sy,sw,sh)。这两个函数都返回带有宽度、高度和数据变量的ImageData对象。数据变量包含以RGBA格式检索的像素数据的一维数组,其中每个值在0到255的范围内变化。要在画布上设置像素,可以使用putImageData(imagedata,dx,dy)函数。

Another way to retrieve the content of the canvas is to store the data into an image. This can be achieved with the Canvas functions save(path) or toDataURL(mimeType), where the later function returns an image URL, which can be used to be loaded by an Image element.

另一种检索画布内容的方法是将数据存储到图像中。这可以通过Canvas函数save(path)或toDataURL(mimeType)实现,后者的函数返回一个图像URL,该图像URL可用于由图像元素类型Image加载。

import QtQuick

Rectangle {
    width: 240; height: 120
    Canvas {
        id: canvas
        x: 10; y: 10
        width: 100; height: 100
        property real hue: 0.0
        onPaint: {
            var ctx = getContext("2d")
            var x = 10 + Math.random(80)*80
            var y = 10 + Math.random(80)*80
            hue += Math.random()*0.1
            if(hue > 1.0) { hue -= 1 }
            ctx.globalAlpha = 0.7
            ctx.fillStyle = Qt.hsla(hue, 0.5, 0.5, 1.0)
            ctx.beginPath()
            ctx.moveTo(x+5,y)
            ctx.arc(x,y, x/10, 0, 360)
            ctx.closePath()
            ctx.fill()
        }
        MouseArea {
            anchors.fill: parent
            onClicked: {
                var url = canvas.toDataURL('image/png')
                print('image url=', url)
                image.source = url
            }
        }
    }

    Image {
        id: image
        x: 130; y: 10
        width: 100; height: 100
    }

    Timer {
        interval: 1000
        running: true
        triggeredOnStart: true
        repeat: true
        onTriggered: canvas.requestPaint()
    }
}

In our little example, we paint every second a small circle on the left canvas. When the user clicks on the mouse area the canvas content is stored and an image URL is retrieved. On the right side of our example, the image is then displayed.

在我们的小示例中,我们每秒在左侧画布上绘制一个小圆圈。当用户单击鼠标区域时,将存储画布内容并检索图像URL。在我们示例的右侧,将显示图像。

 示例源码下载 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值