有必要让QtQuick 2的Canvas元素HiDPI-(视网膜 - )知道吗?

Tob*_*ias 8 canvas qml retina-display

我有以下qml应用程序:

import QtQuick 2.1
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.0
import QtQuick.Window 2.0

ApplicationWindow {
    id: window
    width: 480
    height: 240


    RowLayout {

        Rectangle {
            width: window.height
            height: window.height
            radius: window.height / 2
            color: "black"
        }

        Canvas {
            id: canvas
            width: window.height
            height: window.height

            onPaint: {
                var ctx = canvas.getContext('2d');
                var originX = window.height / 2
                var originY = window.height / 2
                var radius = window.height / 2

                ctx.save();

                ctx.beginPath();
                ctx.arc(originX, originY, radius, 0, 2 * Math.PI);
                ctx.fillStyle = Qt.rgba(0, 0, 0, 1);
                ctx.fill();

                ctx.restore();
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这产生了两个彼此相邻的黑色圆圈.左边的那个(the Rectangle)在Retina显示屏上很清晰,而右边的那个(the Canvas)非常模糊.如果我加

                antialiasing: false
Run Code Online (Sandbox Code Playgroud)

Canvas,它会产生粗糙的模糊像素.

我需要做什么才能Canvas识别HiDPI?

(我在Mac OS X 10.8上使用Qt 5.2.0 beta 1)


编辑:我想出了一个解决方法是包裹CanvasItem,内圈刻度的一切行动onPaint,然后使用transformCanvas规模了回去.

    Canvas {
        id: canvas
        x: 0
        y: 0
        width: parent.width * 2   // really parent.width after the transform
        heigth: parent.height * 2 // really parent.height after the transform

        /* ... */

        // This scales everything down by a factor of two.
        transform: Scale {
            xScale: .5
            yScale: .5
        }

        onPaint: {
            var ctx = canvas.getContext('2d');
            ctx.save();
            ctx.scale(2, 2)       // This scales everything up by a factor of two.

            /* ... */
        }
    }
Run Code Online (Sandbox Code Playgroud)

iBe*_*eve 7

我们使用相同的技巧将大小加倍,然后按比例缩小qml-material中ProgressCircle.但是,您可以进行一些改进:

  1. scale而不是transform.
  2. 使用Screen.devicePixelRatio从所述QtQuick.Window模块而不是在2/0.5硬编码比例因子的.

所以你的代码可以简化为:

Canvas {
    property int ratio: Screen.devicePixelRatio

    width: parent.width * ratio
    heigth: parent.height * ratio
    scale: 1/ratio

    onPaint: {
        var ctx = canvas.getContext('2d');
        ctx.save();
        ctx.scale(ratio, ratio)

        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)