QT使用QML實(shí)現(xiàn)地圖繪制虛線的示例代碼
QML提供了MapPolyline用于在地圖上繪制線段,該線段是實(shí)線,因此我使用Canvas自定義繪制的方式在地圖上繪制線段,如圖:

鼠標(biāo)在地圖上點(diǎn)擊后,在點(diǎn)擊位置添加圖標(biāo) ,當(dāng)有多個(gè)圖標(biāo)被添加到地圖上后,計(jì)算各個(gè)圖標(biāo)間的距離,并創(chuàng)建一個(gè)新的虛線線段組件,連接兩個(gè)圖標(biāo)點(diǎn),顯示距離數(shù)值。如果對自定義圖標(biāo)添加拖動(dòng)屬性,效果如圖:

MapDashLine.qml屬性:
- beginCoordinate:線段起始經(jīng)緯度坐標(biāo)
- endCoordinate:線段終點(diǎn)經(jīng)緯度坐標(biāo)
- lineDash:虛線樣式
- lineColor:虛線顏色
- lineWidth:虛線粗細(xì)
- textColor:顯示距離文字顏色
- textPixelSize:字體大小
MapDashLine.qml源碼(我使用的是Qt5.15):
import QtQuick 2.15
import QtPositioning 5.15
Item {
id:mapDashLine
anchors.fill: parent
property var beginCoordinate: QtPositioning.coordinate()
property var endCoordinate: QtPositioning.coordinate()
property var lineDash: [4,4]
property color lineColor: "crimson"
property int lineWidth: 2
property color textColor: "crimson"
property int textPixelSize: 14
readonly property var mapItem: mapDashLine.parent
Canvas{
id:myCanvas
anchors.fill: parent
onPaint: {
if(!mapDashLine.beginCoordinate.isValid || !mapDashLine.endCoordinate.isValid)
return
var ctx = getContext("2d")
ctx.clearRect(0,0,myCanvas.width,myCanvas.height)
ctx.strokeStyle = mapDashLine.lineColor
ctx.lineWidth = mapDashLine.lineWidth
ctx.setLineDash(mapDashLine.lineDash)
//**繪制虛線
ctx.beginPath()
var beginPos = mapDashLine.mapItem.fromCoordinate(mapDashLine.beginCoordinate,false)
ctx.moveTo(beginPos.x,beginPos.y)
var endPos = mapDashLine.mapItem.fromCoordinate(mapDashLine.endCoordinate,false)
ctx.lineTo(endPos.x,endPos.y)
ctx.stroke()
ctx.save()
//**繪制文字
var azimuth = endCoordinate.azimuthTo(beginCoordinate)
if(azimuth>=180)
azimuth = azimuth - 180
var distance = endCoordinate.distanceTo(beginCoordinate)
var text = (distance/1000).toFixed(0)+"Km"
ctx.fillStyle = mapDashLine.textColor
ctx.font = mapDashLine.textPixelSize+"px Arial"
ctx.textAlign = "center"
var centerX = (beginPos.x+endPos.x)/2
var centerY = (beginPos.y+endPos.y)/2
ctx.translate(centerX,centerY)
ctx.rotate(azimuth*Math.PI/180-Math.PI/2)
ctx.fillText(text,0,-mapDashLine.textPixelSize/2)
ctx.restore()
}
}
onBeginCoordinateChanged: {
update()
}
onEndCoordinateChanged: {
update()
}
onLineDashChanged: {
update()
}
onLineColorChanged: {
update()
}
onLineWidthChanged: {
update()
}
onTextColorChanged: {
update()
}
onTextPixelSizeChanged: {
update()
}
Connections{
target: mapDashLine.mapItem
function onZoomLevelChanged(){
update()
}
function onVisibleRegionChanged(){
update()
}
}
function update(){
myCanvas.requestPaint()
}
}到此這篇關(guān)于QT使用QML實(shí)現(xiàn)地圖繪制虛線的示例代碼的文章就介紹到這了,更多相關(guān)Qt QML地圖繪制虛線內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言基礎(chǔ)之C語言格式化輸出函數(shù)printf詳解
這篇文章主要介紹了C語言格式化輸出函數(shù)printf詳解,printf函數(shù)中用到的格式字符與printf函數(shù)中用到的格式修飾符,感興趣的小伙伴可以借鑒一下2023-03-03
教你使用Matlab制作圖形驗(yàn)證碼生成器(app designer)
這篇文章主要和大家分享如何利用Matlab制作一款圖形驗(yàn)證碼生成器,文中的實(shí)現(xiàn)步驟講解詳細(xì),感興趣的小伙伴可以跟隨小編動(dòng)手試一試2022-02-02

