none
Win8Metro中,如何在程序中绘图? RRS feed

  • 问题

  • 我想在一个page上绘制图像,包括直线,矩形框等,然后将绘制后的图像显示出来。环境是c++/xaml。
    2012年7月31日 2:19

答案

  • 使用WinRT的 Windows.UI.Xaml.Shapes 中的类型来构建可视图形,然后在一个Canvas上利用Pointer的一些移动点击事件来创建图形,例如拖放绘制一个圆形  的实例代码:

    CPP:

    using namespace Windows::UI;
    using namespace Windows::UI::Xaml::Shapes;
    Point pressedStartPoint;
    bool isPressed = false;
    void App6::MainPage::Canvas_PointerPressed(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e)
    {
    	Canvas^ canvas = safe_cast<Canvas^>(sender);
    	ellipse = ref new Ellipse();
    	ellipse->Stroke = ref new SolidColorBrush(Colors::White);
    	ellipse->Fill = ref new SolidColorBrush(Colors::Green);
    	canvas->Children->Append(ellipse);
    	pressedStartPoint = e->GetCurrentPoint(canvas)->Position;
    	ellipse->SetValue(Canvas::LeftProperty, pressedStartPoint.X);
    	ellipse->SetValue(Canvas::TopProperty, pressedStartPoint.Y);
    	canvas->CapturePointer(e->Pointer);
    	isPressed=true;	
    }
    void App6::MainPage::Canvas_PointerMoved(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e)
    {
    	Canvas^ canvas = safe_cast<Canvas^>(sender);
    	Point currentPoint;
    	if (ellipse != nullptr && isPressed)
    	{
    		currentPoint = e->GetCurrentPoint(canvas)->Position;
    		if (currentPoint.X>pressedStartPoint.X)
    			ellipse->Width = currentPoint.X-pressedStartPoint.X;
    		else
    		{
    			ellipse->Width = pressedStartPoint.X-currentPoint.X;
    			ellipse->SetValue(Canvas::LeftProperty, currentPoint.X);
    		}
    		if (currentPoint.Y>pressedStartPoint.Y)
    			ellipse->Height = currentPoint.Y-pressedStartPoint.Y;
    		else
    		{
    			ellipse->Height = pressedStartPoint.Y-currentPoint.Y;
    			ellipse->SetValue(Canvas::TopProperty, currentPoint.Y);
    		}
    	}
    }
    void App6::MainPage::Canvas_PointerReleased(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e)
    {
    	Canvas^ canvas = safe_cast<Canvas^>(sender);
    	canvas->ReleasePointerCapture(e->Pointer);
    	isPressed=false;	
    }


    Header:

    	private:
    		Windows::UI::Xaml::Shapes::Ellipse^ ellipse;
    		void Canvas_PointerPressed(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);
    		void Canvas_PointerMoved(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);
    		void Canvas_PointerReleased(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);

    XAML:

        <Canvas Background="{StaticResource ApplicationPageBackgroundThemeBrush}"
                PointerPressed="Canvas_PointerPressed"
                PointerMoved="Canvas_PointerMoved"
                PointerReleased="Canvas_PointerReleased">
        </Canvas>


    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us

    2012年8月1日 4:57
    版主