我以爲自己早就把這個寫到博客裏了,但是今天需要用到的時候一找才發現沒有。
這是一年前做一個項目時找到的一個用於SL裏圖片平鋪的類,它集成字Canvas,用起來也非常方便。
/// <summary>圖片平鋪
/// </summary>
public class ImageBrushTile : Canvas
{
/// <summary>作用平鋪圖片的高。
/// </summary>
private int imgHeight;
/// <summary>作用平鋪圖片的寬。
/// </summary>
private int imgWidth;
#region ImageSource圖片源
public ImageSource Source
{
get { return (ImageSource)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImageBrushTile),
new PropertyMetadata(null, SourcePropertyChangedCallback));
/// <summary>圖片地址發生變化時調用
/// </summary>
protected static void SourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var exImage = d as ImageBrushTile;
if (exImage != null)
{
exImage.SourceChanged((ImageSource)e.NewValue);
}
}
/// <summary>當Source指定值發生改變時調用。
/// </summary>
protected virtual void SourceChanged(ImageSource imageSource)
{
CalcImageSize(imageSource);
}
#endregion
public ImageBrushTile()
{
CalcImageSize(Source);
SizeChanged += ExImage_SizeChanged;
}
/// <summary>計算Source指定的Image的長和寬.
/// </summary>
private void CalcImageSize(ImageSource imageSource)
{
if (imageSource == null) return;
var img = new Image();
img.ImageOpened += new EventHandler<RoutedEventArgs>(img_ImageOpened);
img.Source = imageSource;
Children.Clear();
//加載圖片到visual tree(視覺樹)裏,爲的是在加載完成後能計算圖片的高和寬。
//img_ImageOpened裏計算。
Children.Add(img);
}
/// <summary>當前控件尺寸改變時調用。
/// </summary>
private void ExImage_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (imgHeight != 0 && imgWidth != 0)
{
CreateImage();
}
}
/// <summary>計算Source指定的Image的長和寬的具體函數,計算填充位置等。
/// </summary>
void img_ImageOpened(object sender, RoutedEventArgs e)
{
var img = sender as Image;
if (img != null)
{
var bitmapSource = img.Source as BitmapSource;
if (bitmapSource != null)
{
imgHeight = bitmapSource.PixelHeight;
imgWidth = bitmapSource.PixelWidth;
Children.Remove(img);
}
}
CreateImage();
}
/// <summary>用指定圖片填充本控件。
/// </summary>
private void CreateImage()
{
if (Source == null) return;
var countX = (int)Math.Ceiling(ActualWidth / imgWidth);
var countY = (int)Math.Ceiling(ActualHeight / imgHeight);
var totalUsedHeight = 0.0;
for (var i = 0; i < countY; i++)
{
var remainHeight = ActualHeight - totalUsedHeight;
var totalUsedWidth = 0.0;
for (var j = 0; j < countX; j++)
{
var remainWidth = ActualWidth - totalUsedWidth;
var img = new Image
{
Stretch = Stretch.None,
Width = remainWidth >= imgWidth ? imgWidth : remainWidth,
Height = remainHeight >= imgHeight ? imgHeight : remainHeight,
Source = Source
};
SetLeft(img, imgWidth * j);
SetTop(img, imgHeight * i);
Children.Add(img);
totalUsedWidth += imgWidth;
}
totalUsedHeight += imgHeight;
}
}
}
前臺使用XAML代碼:
xmlns:my="clr-namespace:SLImageTile"
SLImageTile是項目名稱。
<my:ImageBrushTile Source="/SLImageTile;component/Back.png"/>