[英]How to place a cropped image on a canvas? wpf c#
In my code, I select an image and is cropped into 9 pieces. 在我的代码中,我选择了一张图像并裁剪为9张。 Now I want to randomly position each piece in my canvas.
现在,我想在画布中随机放置每个作品。 How would I go about doing that?
我将如何去做?
public void CutImage(string img)
{
int count = 0;
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(img, UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
objImg[count++] = new CroppedBitmap(src, new Int32Rect(j * 120, i * 120, 120, 120));
}
}
}
public void PositionImage(object[] objImage)
{
for (int i = 0; i < objImage.Length; i++)
{
TranslateTransform translateTransform1 = new TranslateTransform(rnd1.Next(1,360), rnd1.Next(1,360));
}
//movedRectangle.RenderTransform = translateTransform1;
//mainCanvas.Children.Add(movedRectangle);
}
Try the following: 请尝试以下操作:
public void PositionImage(BitmapSource[] objImage)
{
int a, x, y;
BitmapSource t;
Image img;
// Shuffle the array
for (a = 0; a < (objImage.Length * 2); )
{
x = rnd1.Next(objImage.Length);
y = rnd1.Next(objImage.Length);
if (x != y)
{
t = objImage[x];
objImage[x] = objImage[y];
objImage[y] = t;
a++;
}
}
for (a = y = 0; y < 3; y++)
for (x = 0; x < 3; x++)
{
img = new Image();
img.Source = objImage[a++];
img.Width = img.Height = 120;
Canvas.SetLeft(img, x * 120);
Canvas.SetTop(img, y * 120);
mainCanvas.Children.Add(img);
}
}
Is there a requirement that the images must be placed directly onto a canvas element? 是否有必要将图像直接放置在画布元素上? If you know the number of sub-images you will end up with, you can more easily create a series of Image elements in your XAML and then set their Source attribute to the image sub-sections.
如果知道最终得到的子图像数量,则可以更轻松地在XAML中创建一系列Image元素,然后将其Source属性设置为image子部分。
<Canvas>
<Image Name="subimg1">
<Image Name="subimg2">
<Image Name="subimg3">
...
</Canvas>
You'd have individual elements for each sub-image and would be able to move them around the canvas as you wish. 每个子图像都有单独的元素,并且可以根据需要在画布上移动它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.