Skip to main content
 首页 » 编程设计

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

2024年02月13日15tintown

我正在尝试将图像文件从硬盘加载到 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; 
 
   } 

但它不起作用。

请您参考如下方法:

试试这个:

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

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

var pixbuf = new Gdk.Pixbuf ("path\\to\\file"); 

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

更新 我不知道在 gtk# 图像拉伸(stretch)选项中设置任何遗留方法,我通常通过创建新控件来解决这个问题。所以右键单击项目->添加->创建小部件并将名称设置为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); 
    } 
} 

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