2017-03-27 73 views
0

我要畫上的圖像,這是由QQuickPaintedItem子畫和QML創建頂部一些矩形。我使用畫布繪製矩形,可以使用鼠標翻譯和縮放圖像。 下面的代碼不起作用:如何通過壓繪製QtQuick/QML帆布矩形和draging

Canvas{ 
    id:canvas 
    anchors.fill:parent 
    // zoom in/out managed by mouse wheel 
    property double dx:0.0 
    property double dy:0.0 
    property double sx:1.0 
    property double sy:1.0 
    // mapped mouse position will be displayed on the left top of the window 
    property double mx:0 
    property double my:0 
    // mapped mouse postion when last left buttion pressed 
    property double lastx:0.0 
    property double lasty:0.0 
    // flag 
    property bool drawing:false 

    // map x,y to my coordinate 
    function mapToPaint(x,y) 
    { 
     var mx=(x-dx)/sx; 
     var my=(y-dy)/sy; 
     return {"x":mx,"y":my}; 
    } 


    onPaint:{ 
     var ctx = canvas.getContext("2d"); 
     ctx.lineWidth = 1 
     ctx.strokeStyle = Qt.lighter(root.color) 
     ctx.clearRect (0, 0, width, height); 
     ctx.save(); 
     // transform to my coordinate 
     ctx.translate(dx,dy); 
     ctx.scale(sx,sy); 
     // draw a rect 
     // !! I hope drawing can be displayed when mouse moving, 
     // !! but the rect wasn't displayed after the mouse button 
     // !! was released. Instead many rectangles will be showed when 
     // !! I rolled the mouse wheel after the press-drag operation. 
     if(drawing) 
      ctx.rect(lastx,lasty,mx-lastx,my-lasty); 
     ctx.stroke(); 
     ctx.restore(); 
} 
MouseArea { 
    id:area 
    anchors.fill: parent 
    hoverEnabled:true 
    preventStealing:true 
    property double factor: 1.2 
    onPressed: 
    { 

     if (mouse.button == Qt.LeftButton) 
     { 
      var p=canvas.mapToPaint(mouse.x,mouse.y); 
      canvas.lastx=p.x; 
      canvas.lasty=p.y; 
      canvas.drawing=true 
     } 
    } 

    onWheel: 
    { 
     if(wheel.angleDelta.y > 0) // zoom in 
      var zoomFactor = factor 
     else      // zoom out 
      zoomFactor = 1/factor 

     canvas.sx*=zoomFactor; 
     canvas.sy*=zoomFactor; 
     canvas.dx=wheel.x-(wheel.x-canvas.dx)*zoomFactor; 
     canvas.dy=wheel.y-(wheel.y-canvas.dy)*zoomFactor; 
     canvas.requestPaint(); 
    } 
    onPositionChanged: 
    { 
     var p=canvas.mapToPaint(mouse.x,mouse.y); 
     canvas.mx=p.x; 
     canvas.my=p.y; 
     // I hope the rectangle can be showed when draging 
     // but it didn't work!! why? 
     // mouse.button == Qt.LeftButton is always false!!! 
     // so I have to use the canvas.drawing flag 
     // if (mouse.button == Qt.LeftButton) 
     if(canvas.drawing) 
      canvas.requestPaint(); 
    } 

當我按下並拖動鼠標,我得到了下面的圖片:

here

更新:

使用ctx.strokeRect代替的ctx.rect,我得到了正確的矩形,但仍然無法在onPositionChanged中收到鼠標對齊。

here

回答

1

一般來說,你想,如果你需要你的矩形的實時預覽(或其它任何物體)做什麼,你需要創建一個臨時的矩形畫上你的畫布之上,當你點擊它,當你移動鼠標,你只需調整一個矩形的大小,鼠標位置增量的大小,當你放開鼠標,你實際上畫在畫布上的矩形,並刪除預覽。

這就是我要做的,在QML中創建一個臨時矩形非常簡單,所以我想你自己應該沒問題?

你當然也可以在畫布上繪製所有更新,但由於它不是那麼容易,只是刪除最後一個更新,它更容易使用這種方法有一個臨時的覆蓋,我猜。