gpt4 book ai didi

c# - 相当于 WPF 中的 glOrtho

转载 作者:行者123 更新时间:2023-11-30 19:06:12 24 4
gpt4 key购买 nike

在 OpenGL 中我可以这样做:

glOrtho(-10, 10, -10, 10, -1, 1)

建立一个坐标系,其中x的范围是-10到10,y的范围是-10到10。

有没有办法在 WPF 中更改 Canvas 的坐标系?

最佳答案

我在 Canvas 上创建了一个扩展方法,允许您设置笛卡尔坐标系。一个示例调用是:

canvas.SetCoordinateSystem(-10, 10, -10, 10)

这将设置 canvas 的坐标系,使 x 从 -10 到 10,y 从 -10 到 10。

扩展方法如下:

public static Canvas SetCoordinateSystem(this Canvas canvas, Double xMin, Double xMax, Double yMin, Double yMax)
{
var width = xMax - xMin;
var height = yMax - yMin;

var translateX = -xMin;
var translateY = height + yMin;

var group = new TransformGroup();

group.Children.Add(new TranslateTransform(translateX, -translateY));
group.Children.Add(new ScaleTransform(canvas.ActualWidth / width, canvas.ActualHeight / -height));

canvas.RenderTransform = group;

return canvas;
}

这是一个演示程序,它在 Canvas 上绘制 Sin(x) 以及 X 和 Y 轴:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CanvasScale
{
public static class CanvasUtils
{
public static Canvas SetCoordinateSystem(this Canvas canvas, Double xMin, Double xMax, Double yMin, Double yMax)
{
var width = xMax - xMin;
var height = yMax - yMin;

var translateX = -xMin;
var translateY = height + yMin;

var group = new TransformGroup();

group.Children.Add(new TranslateTransform(translateX, -translateY));
group.Children.Add(new ScaleTransform(canvas.ActualWidth / width, canvas.ActualHeight / -height));

canvas.RenderTransform = group;

return canvas;
}
}

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

var canvas = new Canvas();

Content = canvas;

SizeChanged += (s, e) => canvas.SetCoordinateSystem(-10, 10, -10, 10);

canvas.Children.Add(new Line() { X1 = -10, Y1 = 0, X2 = 10, Y2 = 0, Stroke = Brushes.Black, StrokeThickness = 0.2 });
canvas.Children.Add(new Line() { X1 = 0, Y1 = -10, X2 = 0, Y2 = 10, Stroke = Brushes.Black, StrokeThickness = 0.2 });

var polyline = new Polyline()
{
Stroke = Brushes.BurlyWood,
StrokeThickness = 0.1,
Points = new PointCollection()
};

for (var x = -10.0; x <= 10.0; x += 0.1)
polyline.Points.Add(new Point(x, Math.Sin(x)));

canvas.Children.Add(polyline);
}
}
}

这是它的样子:

enter image description here

关于c# - 相当于 WPF 中的 glOrtho,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13079610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com