我以为自己早就把这个写到博客里了,但是今天需要用到的时候一找才发现没有。
这是一年前做一个项目时找到的一个用于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"/>