在 GTK 中将 Pixbuf 加载到图像小部件#

tec*_*hno 1 c# gtk# monodevelop

我正在尝试将图像文件从硬盘加载到 GTK# 中的图像小部件。我知道 Pixbuf 用于表示图像。在我使用过的 .net 中 Bitmap b=Bitmap.from File ("c:\windows\file.jpg")

并分配PictureBox=b;

我怎么能做到这一点 Image Widget

更新:

我试过

protected void OnButton2ButtonPressEvent (object o, ButtonPressEventArgs args)
    {
        var buffer = System.IO.File.ReadAllBytes ("i:\\Penguins.jpg");
        var pixbuf = new Gdk.Pixbuf (buffer);
        image103.Pixbuf = pixbuf;

   }
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

Def*_*iss 5

尝试这个:

var buffer = System.IO.File.ReadAllBytes ("path\\to\\file");
var pixbuf = new Gdk.Pixbuf (buffer);
image.Pixbuf = pixbuf;
Run Code Online (Sandbox Code Playgroud)

你也可以像这样创建一个 pixbuf:

var pixbuf = new Gdk.Pixbuf ("path\\to\\file");
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将此构造函数与包含一些俄语符号的路径一起使用时,由于编码错误,我遇到了异常。

更新 我不知道在 gtk# 图像拉伸选项中设置任何遗留方法,我通常通过创建新控件来解决这个问题。所以右键单击项目->添加->创建小部件并将名称设置为ImageControl。在创建的小部件上添加图像。然后像这样编辑ImageControl的代码:

[System.ComponentModel.ToolboxItem (true)]
public partial class ImageControl : Gtk.Bin
{

    private Pixbuf original;

    private bool resized;

    public Gdk.Pixbuf Pixbuf {
        get
        { 
            return image.Pixbuf;
        }
        set
        { 
            original = value;
            image.Pixbuf = value;
        }
    }

    public ImageControl ()
    {
        this.Build ();
    }
    protected override void OnSizeAllocated (Gdk.Rectangle allocation)
    {
        if ((image.Pixbuf != null) && (!resized)) {
            var srcWidth = original.Width;
            var srcHeight = original.Height;
            int resultWidth, resultHeight;
            ScaleRatio (srcWidth, srcHeight, allocation.Width, allocation.Height, out resultWidth, out resultHeight);
            image.Pixbuf = original.ScaleSimple (resultWidth, resultHeight, InterpType.Bilinear);
            resized = true;
        } else {
            resized = false;
            base.OnSizeAllocated (allocation);
        }
    }

    private static void ScaleRatio(int srcWidth, int srcHeight, int destWidth, int destHeight, out int resultWidth, out int resultHeight)
    {
        var widthRatio = (float)destWidth / srcWidth;
        var heigthRatio = (float)destHeight / srcHeight;

        var ratio = Math.Min(widthRatio, heigthRatio);
        resultHeight = (int)(srcHeight * ratio);
        resultWidth = (int)(srcWidth * ratio);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用ImageControl小部件的Pixbuf属性设置图片。