試試這個:
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#image 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);
}
}
現在你可以設置圖片與PIXBUFImageControl財產的部件。
請參閱編輯 – techno
@techno什麼意思是「不起作用」?你有沒有更新的例外或你的控制權? – Deffiss
控件沒有更新,沒有錯誤 – techno