为什么不能用cairo在winform上绘制面板

时间:2013-05-02 07:28:22

标签: c# mono cairo

我在窗户上有开罗,我不知道为什么它不能在我的面板上画画 当我使用GDI时,一切都是oke,但是当我使用cairo时我无法画画,请帮忙。 谢谢。


包裹开罗画画

using System;
using Cairo;
using Gtk;  
namespace BT.LibExtend
{
    public class CairoExt : BTGraphicLibExt 
    {
        Surface s;
        Context c;
        public CairoExt(IntPtr hdc)
        {
            s = new Win32Surface(hdc);
            c = new Context(s);
        }
        public override void DrawLine(double x1, double y1, double x2, double y2)
        {
            c.MoveTo(x1, y1);
            c.LineTo(x2, y2);
            c.Stroke();
        }
    }
}

这是myform

   public partial class FigureDraw : Form
{
    GraphicLibExt glip;

    public FigureDraw()
    {
        InitializeComponent();
        glip = new CairoExt(pnMainDraw.CreateGraphics().GetHdc());

    }

    private void btnLine_Click(object sender, EventArgs e)
    {
        glip.DrawLine(20, 20, 100, 100);
    }

}

1 个答案:

答案 0 :(得分:0)

在显示窗口之前,可能无法获取deive上下文,但我不确定。

在覆盖的OnPaint方法中使用PaintEventArgs的图形时,它可以正常工作。

using System.Windows.Forms;
using Cairo;
using Color = Cairo.Color;
using Graphics = System.Drawing.Graphics;

public partial class Form1 : Form
{
    public Graphics Graphics1 { get; private set; }
    public Context Context1 { get; set; }
    public Win32Surface Surface1 { get; private set; }

    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        Graphics1 = e.Graphics;
        Surface1 = new Win32Surface(Graphics1.GetHdc());
        Context1 = new Context(Surface1);

        var p1 = new PointD(10, 10);
        var p2 = new PointD(100, 10);
        var p3 = new PointD(100, 100);
        var p4 = new PointD(10, 100);

        Context1.MoveTo(p1);
        Context1.LineTo(p2);
        Context1.LineTo(p3);
        Context1.LineTo(p4);
        Context1.LineTo(p1);
        Context1.ClosePath();
        Context1.Fill();

        Context1.MoveTo(140, 110);
        Context1.SetFontSize(32);
        Context1.SetSourceColor(new Color(0,0,0.8,1));
        Context1.ShowText("Hello Cairo!");

        Graphics1.Dispose();
        Context1.Dispose();
        Surface1.Dispose();
    }
}

或者使用本机方法GetDc来获取hdc when the form is shown