我创建了一个UI文本组件,该组件将在我的游戏引擎(UWP)中在屏幕上绘制文本。但是,由于分辨率缩放,我在定位方面遇到问题。在我的笔记本电脑屏幕上(分辨率比例为2),它看起来不错,但是在我的外接显示器(分辨率比例为1)上,文本略有偏移。
这是UI文本组件的呈现代码:
void TextComponent::Render(shared_ptr<AmberDevice> device, ShaderConfiguration& configuration)
{
auto context = m_device->GetProperties().GetD2DDeviceContext();
context->SaveDrawingState(m_stateBlock.Get());
context->BeginDraw();
device->ApplyTextTransform(GetTransform());
context->DrawTextLayout(
Point2(0.0f, 0.0f),
m_layout.Get(),
m_brush.Get());
context->EndDraw();
context->RestoreDrawingState(m_stateBlock.Get());
}
ApplyTextTransform方法如下所示(进行实际的翻译计算):
void AmberDevice::ApplyTextTransform(Amber::Scene::Transform2D transform)
{
auto size = transform.GetSize();
auto scaling = transform.GetScale();
auto rotation = transform.GetRotation();
auto translation = transform.GetPosition();
auto pivot = transform.GetPivot();
auto screenSize = m_properties.GetRenderOutputSize();
auto scaleFactor = m_properties.GetResolutionScale();
Matrix3x2F translate = Matrix3x2F::Translation(
(translation.x / scaleFactor) + (screenSize.x / (scaleFactor * 2.f)),
-(translation.y / scaleFactor) + (screenSize.y / (scaleFactor * 2.f)));
Matrix3x2F scale = Matrix3x2F::Scale(Size(scaling.x, scaling.y), center);
Matrix3x2F rotate = Matrix3x2F::Rotation(rotation, center);
m_properties.GetD2DDeviceContext()->SetTransform(
scale * rotate * translate * m_properties.GetOrientationTransform2D());
}
我将屏幕尺寸和组件的位置除以分辨率比例,以对其进行归一化,并使其获得与系统逻辑分辨率相同的分辨率(即非比例缩放)。我将逻辑屏幕的宽度和高度添加到最终转换的一半,这样我就可以在屏幕中央获得0,0,使其类似于在D3D正交网格中绘制子画面的方式。