Qt5.15中Qt3D材质纹理旋转与缩放实现问题
Qt3D中纹理的旋转与缩放实现
问题背景
使用Qt 5.15基于Qt3D.Extras、Qt3D.Core等模块开发项目,已通过Texture2D { TextureImage { source: "file:res1.png" }}为DiffuseSpecularMaterial的diffuse属性设置纹理,但无法实现纹理的旋转或缩放,且无法迁移至QtQuick3D。
实现方案
在Qt3D中,纹理的变换需要通过TextureTransform组件结合矩阵变换来完成,具体步骤:
- 给
Texture2D添加textureTransform属性,关联TextureTransform组件 - 通过
TextureTransform的matrix属性定义缩放、旋转等变换矩阵
变换矩阵常用操作
- 缩放:
Qt.matrix4x4().scale(sx, sy, 1),sx、sy为X/Y轴缩放比例 - 旋转:
Qt.matrix4x4().rotate(angle, 0, 0, 1),angle为旋转角度(顺时针为正,单位:度) - 平移:
Qt.matrix4x4().translate(tx, ty, 0),tx、ty为X/Y轴偏移量 - 组合变换:可链式调用多个变换方法,注意变换顺序(通常先旋转/缩放,再平移)
修改后的代码
完整main.qml代码
import QtQuick import QtQuick.Window import Qt3D.Core import Qt3D.Render import Qt3D.Input import Qt3D.Extras import QtQuick.Scene3D Window { width: 640 height: 480 visible: true title: qsTr("Hello World") Scene3D { id: id_Scene3d anchors.fill: parent anchors.margins: 10 focus: true aspects: ["input", "logic"] cameraAspectRatioMode: Scene3D.AutomaticAspectRatio Entity { id: id_SceneRootEntity Camera { id: id_Camera projectionType: CameraLens.PerspectiveProjection fieldOfView: 45 nearPlane : 0.1 farPlane : 1000.0 position: Qt.vector3d( -20.0, 20.0, 40.0 ) upVector: Qt.vector3d( 0.0, 1.0, 0.0 ) viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 ) } OrbitCameraController { camera: id_Camera lookSpeed: 150 linearSpeed: 200 } components: [ RenderSettings { id: id_RenderSettings activeFrameGraph: ForwardRenderer { camera: id_Camera clearColor: "transparent" showDebugOverlay: false } }, InputSettings { } ] Entity { components: [ PlaneMesh { height: 5; width: 7 } , DiffuseSpecularMaterial { ambient: "white" diffuse: Texture2D { TextureImage { source: "file:res1.png" } // 配置纹理变换:缩放2倍、旋转45度 textureTransform: TextureTransform { matrix: Qt.matrix4x4() .scale(2, 2, 1) .rotate(45, 0, 0, 1) } } } ] } } } }
说明
.pro和main.cpp文件无需修改,保持原内容即可- 可根据需求调整
matrix中的变换参数,实现不同的纹理效果
内容的提问来源于stack exchange,提问作者Prain
相关产品推荐
相关产品推荐

