2010-07-04 60 views
5

我發展在WPF .NET 3.5的自定義圖像控制和Visual Studio 2010WPF如何中心

在的WinForms的PicutreBox控制有SizeMode財產包括Image.Source「CenterImage「。

我想讓我的圖片控件擁有該能力。

反正有嗎?

感謝

我的XAML代碼:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="768" Width="1024" xmlns:my="http://schemas.sharpsoft.net/xaml" xmlns:my1="clr-namespace:WpfApplication1"> 
    <Grid> 
     <my1:CustomControl1 
        x:Name="customControl11" 
        Width="206" 
        Height="197" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Top" 
        Margin="18,58,0,0" 
        Stretch="Uniform"/> 
    </Grid> 
</Window> 

我CustomControl代碼:

public class CustomControl1 : Image 
{ 
    public CustomControl1() 
    { 
     // Bitmap to Stream 
     Stream ms = new MemoryStream(); 
     Properties.Resources.webcam_background.Save(ms, ImageFormat.Png); 

     // Stream to BitmapImage 
     BitmapImage bitmap = new BitmapImage(); 
     bitmap.BeginInit(); 
     bitmap.StreamSource = ms; 
     bitmap.EndInit(); 

     // Set it 
     Source = bitmap; 
    } 
} 

其中 「webcam_backgroud」 是默認的Visual Studio資源編輯器中添加PNG圖像。

回答

2

Stretch設置爲無。

<Image Source="..." Stretch="None" /> 
+0

我已經嘗試過,但它沒有得到我期望的效果。現在它減少了我的形象並將其放在左上角。 無:http://img28.imageshack.us/img28/1783/imagestretchnone.png 統一:http://img810.imageshack.us/img810/2401/imagestretchuniform.png – JoanComasFdz 2010-07-04 15:42:28

+0

@unexpectedkas:你可以編輯你的問題包括你的一些XAML?該圖像將在默認情況下在圖像控件中居中繪製,但圖像控件可能不會居中或跨父元素拉伸。例如,如果你的整個窗口是一個帶有一個Image的Grid,那麼它將會居中,但如果它是一個帶有一個Image的Canvas,那麼它將位於左上角。 – Quartermeister 2010-07-04 16:28:34

+0

好吧,我剛剛做到了。 我將H/V align設置爲中心,並且是,圖像中心。非常感謝。無論如何看它的權利拉伸必須是「統一」。 我很困惑,因爲控制窗口移動¬¬' – JoanComasFdz 2010-07-04 17:58:27

5

你應該嘗試使用居中對齊整個Image元素本身:

<Grid> 
     <Image Stretch="None" 
       HorizontalAlignment="Center" 
       VerticalAlignment="Center" /> 
    </Grid> 
+0

是的,我做到了。但由於某種原因,控制會呈現出一種「縮略圖」,而不是原來的那種。我認爲這是因爲我在編寫資源的方式,那就是不使用URI。 – JoanComasFdz 2010-07-06 13:42:58

-2

只要給一個X:在窗口名稱,檢索它的尺寸信息。

<Window x:Name="mainWindowContainer" 
    x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="768" Width="1024" xmlns:my="http://schemas.sharpsoft.net 
    [...] 
</Window> 

再回想從code.Then窗口的實際大小的信息,因爲你有託管大小和物體的大小,它只是數學。陳述的幀大小all'around 'frameWidth' 的背景下,圖像的(destWidth,destHeight)的尺寸,可以設置:

 int wOffset = (((int)mainWindowContainer.ActualWidth - frameWidth * 2) - destWidth)/2 + frameWidth; 
     int hOffset = (((int)mainWindowContainer.ActualHeight - frameWidth * 2) - destHeight)/2 + frameWidth; 

     Canvas.SetLeft(image, wOffset); 
     Canvas.SetTop(image, hOffset); 
0

這是我工作的解決方案:

<Image Name="PreviewImage" HorizontalAlignment="Stretch" Stretch="Uniform" VerticalAlignment="Top" Width="456" Height="256"/>