i am developing an app in which i ant to do some work in background and in the the ui the the timer should run like starts in 3 2 1 and then by that time my manipulation will be completed . but the issue is that is that even my methods are async my UI is getting blocked.
my code is
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
Task<WriteableBitmap> transparentbordertemp = Render("tilenew.png");
Task<WriteableBitmap> transparentbitmaptemp = Render("greenpattern.png");
if (GameSettingData.mainimageselected == null)
{
bitmapimagemain = await Render("puzzleimage.png");
bitmapimagemain = bitmapimagemain.Resize(550, 550, WriteableBitmapExtensions.Interpolation.Bilinear);
puzzleimage.Source = bitmapimagemain;
GameSettingData.mainimageselected = bitmapimagemain;
}
else
{
bitmapimagemain = GameSettingData.mainimageselected;
bitmapimagemain = bitmapimagemain.Resize(550, 550, WriteableBitmapExtensions.Interpolation.Bilinear);
puzzleimage.Source = bitmapimagemain;
}
height = (puzzleimage.Parent as Grid).ActualHeight + 15;
width = (puzzleimage.Parent as Grid).ActualWidth - 25;
double startx = 0;
double starty = 0;
heightpiece = 546 / numberofrows;
widhpiece = 550 / numberofrows;
animationgrid.Height = heightpiece + 100;
animationgrid.Width = widhpiece + 100;
Rect rectangle;
int counter = 0;
WriteableBitmap transparentborder = new WriteableBitmap(330, 330);
finalbitmapimage = bitmapimagemain;
finalbitmapimage = finalbitmapimage.Resize(330 * numberofrows, 330 * numberofrows, WriteableBitmapExtensions.Interpolation.Bilinear);
int blithelpx = 0;
int blithelpy = 0;
for (int i = 0; i < numberofrows; i++)
{
for (int j = 0; j < numberofrows; j++)
{
imagepeices = new Image();
imagepeices.Height = bitmapimagemain.PixelHeight / (2 * numberofrows);
imagepeices.Width = bitmapimagemain.PixelWidth / (2 * numberofrows);
imagepeices.Stretch = Stretch.Uniform;
counter++;
imagepeices.Tag = counter;
startx = j * bitmapimagemain.PixelWidth / numberofrows;
starty = i * bitmapimagemain.PixelHeight / numberofrows;
rectangle = new Rect(startx, starty, bitmapimagemain.PixelWidth / numberofrows, bitmapimagemain.PixelHeight / numberofrows);
WriteableBitmap bitmapimagemain1 = bitmapimagemain.Crop(rectangle).Resize(330, 330, WriteableBitmapExtensions.Interpolation.Bilinear);
// transparentborder = await Render("tilenew.png");
transparentborder = await transparentbordertemp;
transparentborder = transparentborder.Resize(330, 330, WriteableBitmapExtensions.Interpolation.Bilinear);
final = new WriteableBitmap(transparentborder.PixelWidth, transparentborder.PixelHeight);
final.Blit(new Rect(0, 0, (int)bitmapimagemain1.PixelWidth, (int)bitmapimagemain1.PixelHeight), bitmapimagemain1, new Rect(0, 0, (int)bitmapimagemain1.PixelWidth, (int)bitmapimagemain1.PixelHeight), WriteableBitmapExtensions.BlendMode.Additive);
final.Blit(new Rect(0, 0, (int)transparentborder.PixelWidth, (int)transparentborder.PixelHeight), transparentborder, new Rect(0, 0, (int)transparentborder.PixelWidth, (int)transparentborder.PixelHeight), WriteableBitmapExtensions.BlendMode.Additive);
final = final.Resize((int)widhpiece, (int)widhpiece, WriteableBitmapExtensions.Interpolation.Bilinear);
imagepeices.Source = final;
imagepeices.PointerPressed += ImagePointerPressed;
imagepeices.PointerReleased += ImagePointerReleased;
imagepeices.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
imagepeices.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
listimages.Add(imagepeices);
bitmaplist.Add(bitmapimagemain.Crop(rectangle));
margin += 20;
gridpieces.Children.Add(imagepeices);
finalbitmapimage.Blit(new Rect(blithelpx, blithelpy, (int)transparentborder.PixelWidth, (int)transparentborder.PixelHeight), transparentborder, new Rect(0, 0, (int)transparentborder.PixelWidth, (int)transparentborder.PixelHeight), WriteableBitmapExtensions.BlendMode.Additive);
blithelpx += 330;
}
blithelpx = 0;
blithelpy += 330;
}
foreach (Image item in listimages)
{
var a = (item.Parent as Grid).ActualHeight;
var b = (item.Parent as Grid).ActualWidth;
var x = rand.Next(50, 250);
var y = rand.Next(100, 400);
transformpoints.Add(new Point(x, y));
TranslateTransform posTransform = new TranslateTransform();
posTransform.X = x;
posTransform.Y = y;
item.RenderTransform = posTransform;
}
newgrid = new Grid();
RowDefinition[] rows = new RowDefinition[numberofrows];
ColumnDefinition[] columns = new ColumnDefinition[numberofrows];
for (int q = 0; q < numberofrows; q++)
{
columns[q] = new ColumnDefinition();
columns[q].Width = new GridLength(1, GridUnitType.Star);
newgrid.ColumnDefinitions.Add(columns[q]);
}
for (int t = 0; t < numberofrows; t++)
{
rows[t] = new RowDefinition();
rows[t].Height = new GridLength(1, GridUnitType.Star);
newgrid.RowDefinitions.Add(rows[t]);
}
int counter1 = 0;
startx = 0;
starty = 0;
counter = 0;
for (int p = 0; p < numberofrows; p++)
{
for (int u = 0; u < numberofrows; u++)
{
counter1++;
Grid qwe = new Grid() { Name = "asd" + counter1.ToString(), Tag = counter1, Margin = new Thickness(0, 0, 0, 0) };
Image transparentimage = new Image();
transparentimage.Stretch = Stretch.Uniform;
WriteableBitmap transparentbitmap = await transparentbitmaptemp;
transparentbitmap = transparentbitmap.Resize(330, 330, WriteableBitmapExtensions.Interpolation.Bilinear);
Image imageblur = new Image();
imageblur.Stretch = Stretch.Uniform;
imageblur.Source = transparentbitmap;
imageblur.Height = transparentbitmap.PixelHeight;
imageblur.Width = transparentbitmap.PixelWidth;
if (u == 0)
{
imageblur.Margin = new Thickness(10, 0, -20, 1);
}
else if (u == numberofrows - 1)
{
imageblur.Margin = new Thickness(0, 0, 0, 1);
}
else
{
if (u == 1)
{
imageblur.Margin = new Thickness(0, 0, -13, 1);
}
else
{
imageblur.Margin = new Thickness(-13, 0, -13, 1);
}
}
transparentimage.Source = final;
qwe.Height = heightpiece;
qwe.Width = widhpiece;
qwe.Children.Add(imageblur);
qwe.Opacity = .6;
Grid.SetColumn(qwe, u);
Grid.SetRow(qwe, p);
newgrid.Children.Add(qwe);
}
}
newgrid.Margin = new Thickness(10, 0, 10, 0);
imagegrid.Children.Add(newgrid);
puzzleimage.Source = finalbitmapimage;
disabletopbar = 0;
initialcountdowngrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
imagegrid.Opacity = 1;
gridpieces.Opacity = 1;
dispatchertimer.Start();
}
and my render method is
private async Task<WriteableBitmap> Render(string filename)
{
var Assets = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("JumblerGame");
var folder = await Assets.GetFolderAsync("Images");
StorageFile file1 = await folder.GetFileAsync(filename);
BitmapImage i1 = new BitmapImage();
using (IRandomAccessStream strm = await file1.OpenReadAsync())
{
i1.SetSource(strm);
}
WriteableBitmap img1 = new WriteableBitmap(i1.PixelWidth, i1.PixelHeight);
using (IRandomAccessStream strm = await file1.OpenReadAsync())
{
img1.SetSource(strm);
}
return img1;
}
and in my on navigation i have started a timer on the ui but the timer does not start untill this async method is executed.
i dont understand why ...
All the code with all for loops and image processing in PageLoaded is executed on the UI thread, so that probably what is preventing the dispatcher time to execute.
You could add await Task.Delay(10); inside the for loops to free a little of the UI thread. You could also use await Task.Run(()=>{ ....}); to execute the image processing on WriteableBitmap which don't need to be executed on the UI thread
Related
Store an image with the ".raw" extension in a two-dimensional byte array. Convert it to bitmap. I want to show this in the picture box, but if I run it with the code below, I get an error that the parameter is wrong.
Width and height are obtained from the information provided by the header file.
I wonder what I'm doing wrong.
string filename = #"test.raw";
byte[] rawBytes = File.ReadAllBytes(filename);
int bytePixel = 2;
int width = samples*bytePixel;
int height = lines;
byte[,] rawData = new byte[height, width];
int counter = new int();
for(int i = 0; i < height; i++)
{
for(int j = 0; j < width; j++, counter++)
{
rawData[i, j] = rawBytes[counter];
}
}
Bitmap bitmapImage = new Bitmap(width, height, PixelFormat.Format16bppGrayScale);
BitmapData bitmapImageData = bitmapImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormap.Format16bppGrayScale);
unsafe
{
byte* pointer = (byte*)bitmapImageData.Scan0.ToPointer();
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++, pointer++)
{
*pointer = rawData[y, x];
}
}
}
bitmapImage.UnlockBits(bitmapImageData);
pictureBox1.Image = bitmapImage;
Please give me some advice.
I can't figure out what's wrong but if you just want to see byte array result on screen, this func will make bmp file with IntPtr. Hope it helps.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var fs = new FileStream("test.bmp", FileMode.Open);
Bitmap bitmap = new Bitmap(800, 600, PixelFormat.Format16bppGrayScale);
BitmapData bitmapdata = bitmap.LockBits(new Rectangle(0, 0, 800, 600), ImageLockMode.WriteOnly, PixelFormat.Format16bppGrayScale);
unsafe
{
byte* p = (byte*)bitmapdata.Scan0.ToPointer();
for (int i = 0; i < 600; i++)
{
for (int j = 0; j < 800; j++)
{
*p = (byte)(i * j); p++;
}
}
}
FileSaveBMP($"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.bmp", bitmapdata.Scan0, new CRect() { Width = 800, Height = 600 }, 800);
bitmap.UnlockBits(bitmapdata);
//pictureBox1.Image = bitmap;
}
private unsafe void FileSaveBMP(string sFile, IntPtr ptr, CRect rect, int w, int p_nByte = 1)
{
FileStream fs = new FileStream(sFile, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(Convert.ToUInt16(0x4d42));
if (p_nByte == 1)
{
if ((Int64)rect.Width * (Int64)rect.Height > Int32.MaxValue) bw.Write(Convert.ToUInt32(54 + 1024 + p_nByte * 1000 * 1000));
else bw.Write(Convert.ToUInt32(54 + 1024 + p_nByte * (Int64)rect.Width * (Int64)rect.Height));
}
else if (p_nByte == 3)
{
if ((Int64)rect.Width * (Int64)rect.Height > Int32.MaxValue) bw.Write(Convert.ToUInt32(54 + p_nByte * 1000 * 1000));//uint bfSize = br.ReadUInt32();
else bw.Write(Convert.ToUInt32(54 + p_nByte * (Int64)rect.Width * (Int64)rect.Height));//uint bfSize = br.ReadUInt32();
}
//image 크기 bw.Write(); bmfh.bfSize = sizeof(14byte) + nSizeHdr + rect.right * rect.bottom;
bw.Write(Convert.ToUInt16(0)); //reserved // br.ReadUInt16();
bw.Write(Convert.ToUInt16(0)); //reserved //br.ReadUInt16();
if (p_nByte == 1)
bw.Write(Convert.ToUInt32(1078));
else if (p_nByte == 3)
bw.Write(Convert.ToUInt32(54));//uint bfOffBits = br.ReadUInt32();
bw.Write(Convert.ToUInt32(40));// uint biSize = br.ReadUInt32();
bw.Write(Convert.ToInt32(rect.Width));// nWidth = br.ReadInt32();
bw.Write(Convert.ToInt32(rect.Height));// nHeight = br.ReadInt32();
bw.Write(Convert.ToUInt16(1));// a = br.ReadUInt16();
bw.Write(Convert.ToUInt16(8 * p_nByte)); //byte // nByte = br.ReadUInt16() / 8;
bw.Write(Convert.ToUInt32(0)); //compress //b = br.ReadUInt32();
if ((Int64)rect.Width * (Int64)rect.Height > Int32.MaxValue) bw.Write(Convert.ToUInt32(1000 * 1000));// b = br.ReadUInt32();
else bw.Write(Convert.ToUInt32((Int64)rect.Width * (Int64)rect.Height));// b = br.ReadUInt32();
bw.Write(Convert.ToInt32(0));//a = br.ReadInt32();
bw.Write(Convert.ToInt32(0));// a = br.ReadInt32();
bw.Write(Convert.ToUInt32(256)); //color //b = br.ReadUInt32();
bw.Write(Convert.ToUInt32(256)); //import // b = br.ReadUInt32();
if (p_nByte == 1)
{
for (int i = 0; i < 256; i++)
{
bw.Write(Convert.ToByte(i));
bw.Write(Convert.ToByte(i));
bw.Write(Convert.ToByte(i));
bw.Write(Convert.ToByte(255));
}
}
if (rect.Width % 4 != 0)
{
rect.Right += 4 - rect.Width % 4;
}
byte[] aBuf = new byte[p_nByte * rect.Width];
for (int i = rect.Height - 1; i >= 0; i--)
{
Marshal.Copy((IntPtr)((long)ptr + rect.Left + ((long)i + (long)rect.Top) * w * p_nByte), aBuf, 0, rect.Width * p_nByte);
bw.Write(aBuf);
}
bw.Close();
fs.Close();
}
}
public class CRect
{
public int Left
{
get; set;
}
public int Right
{
get; set;
}
public int Top
{
get; set;
}
public int Bottom
{
get; set;
}
public int Width
{
get; set;
}
public int Height
{
get; set;
}
}
Above code creates image file like this.
enter image description here
I have captured points data from bamboo slate,and converted them to Windows.UI.Input.Inking.InkStroke data.Then I put them in a InkPresenter.StrokeContainer rendered like this image above.Strokes sticked to each other,how can I seperate them?
This is my code below.
private void DataDisplay()
{
List<InkPoint> list = new List<InkPoint>();
List<InkStroke> strokes = new List<InkStroke>();
InkDrawingAttributes drawingAttributes1 = new InkDrawingAttributes();
drawingAttributes1.Color = Colors.Black;
drawingAttributes1.Size = new Size(1, 1);
InkStrokeBuilder builder = new InkStrokeBuilder();
builder.SetDefaultDrawingAttributes(drawingAttributes1);
inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes1);
inkCanvas.InkPresenter.IsInputEnabled = true;
foreach (var item in data.Stroke)
{
string[] strArray = item.Split(',');
for (int i = 9; i <= strArray.Length - 5; i += 5)
{
float x = float.Parse(strArray[i]) / 30;
float y = float.Parse(strArray[i + 1]) / 30;
float pressure = float.Parse(strArray[i + 2]) / 1000;
Point point = new Point(x, y);
InkPoint ip = new InkPoint(point, pressure);
list.Add(ip);
}
Matrix3x2 matrix3X2 = new Matrix3x2(1, 0, 0, 1, 0, 0);
InkStroke newStroke = builder.CreateStrokeFromInkPoints(list, matrix3X2);
strokes.Add(newStroke);
}
inkCanvas.InkPresenter.StrokeContainer.AddStroke(strokes);
}
This is a little project for myself, just learning graphics for WinForms and so on.
The goal is to program my own Calendar control which will meet some very specific requirements.
Here's how I handle the Paint Event (very hacky atm):
private void XCalendar_Paint(object sender, PaintEventArgs e)
{
// Pen
var pen_border = new Pen(BorderColorGrid);
var pen_row_border = new Pen(BorderColorGridRow);
var pen_column_border = new Pen(BorderColorGridColumn);
//var grid_pen = new Pen(Color.Black);
var bez_pen = new Pen(Color.FromArgb(192, 241, 231));
var description_row_height = 30;
var description_column_width = 65;
// Calculate Full
int full_width = this.Width - 1 - description_column_width;
int full_height = this.Height - 1 - description_row_height;
if (this.Users.Count == 0)
{
var s = "Keine Benutzer gefunden.";
var f = new Font(new FontFamily("Trebuchet MS"), 12f);
var s_size = e.Graphics.MeasureString(s, f);
var p = new Point((int)(full_width / 2) - (int)(s_size.Width / 2) + 30, 30);
e.Graphics.DrawString(s, f, new SolidBrush(Color.FromArgb(180, 180, 180)), p);
return;
}
// Calculate Rows
int row_count = 0;
switch (_calendarView)
{
case CalendarViews.Day:
row_count = 1;
break;
case CalendarViews.Week:
row_count = 7;
break;
case CalendarViews.Month:
row_count = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
break;
}
int row_height = full_height / row_count;
// Calculate Columns
int col_count = Users.Count;
int col_width = full_width / col_count;
// Draw Description Column BackColor
var desc_col_rect = new Rectangle(new Point(1, description_row_height + 1), new Size(description_column_width - 1, full_height - 1));
e.Graphics.FillRectangle(new SolidBrush(bez_pen.Color), desc_col_rect);
// Draw Border
var rect = new Rectangle(new Point(0, 0), new Size(this.Width - 1, this.Height - 1));
e.Graphics.DrawRectangle(pen_border, rect);
var desc_font = new Font(new FontFamily("Trebuchet MS"), 9f);
var desc_brush = new SolidBrush(Color.Black);
// Draw Columns
var col_x = description_column_width;
for (int x = 0; x < col_count; x++)
{
var rect_col = new Rectangle(new Point(col_x, 1), new Size(col_width, description_row_height));
var user = Users[x];
var short_name = user.Shortname;
var desc_size = e.Graphics.MeasureString(short_name, desc_font);
e.Graphics.FillRectangle(new SolidBrush(user.Color), rect_col);
e.Graphics.DrawLine(pen_column_border, new Point(col_x, 0), new Point(col_x, full_height + description_row_height));
e.Graphics.DrawString(short_name, desc_font, desc_brush, new Point(col_x + (int)(col_width / 2 - desc_size.Width / 2), (int)(description_row_height / 2 - desc_size.Height / 2)));
col_x += col_width;
}
// Draw Rows
var row_y = description_row_height;
DateTime dt = this.StartDateTime == null ? DateTime.Now : StartDateTime;
switch (this._calendarView)
{
case CalendarViews.Week:
dt = DateTimeExtensions.StartOfWeek(dt, DayOfWeek.Monday);
break;
case CalendarViews.Month:
dt = new DateTime(dt.Year, dt.Month, 1);
break;
}
for (int x = 0; x < row_count; x++)
{
var rect_row = new Rectangle(new Point(1, row_y), new Size(description_column_width - 1, row_height));
var s = new DateTimeFormatInfo().GetShortestDayName(dt.DayOfWeek) + ", " + dt.ToString("dd.MM");
var cur_row_fill_color = Color.Transparent;
if (dt.Date == DateTime.Now.Date)
{
cur_row_fill_color = this.FillColorCurrentDateRow;
}
else if (dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)
{
cur_row_fill_color = this.FillColorWeekendDays;
}
var s_size = e.Graphics.MeasureString(s, desc_font);
e.Graphics.FillRectangle(new SolidBrush(cur_row_fill_color), rect_row);
e.Graphics.DrawLine(pen_row_border, new Point(0, row_y), new Point(full_width + description_column_width, row_y));
e.Graphics.DrawString(s, desc_font, desc_brush, new Point((int)(description_column_width / 2 - s_size.Width / 2), row_y + 3));
dt = dt.AddDays(1);
row_y += row_height;
}
}
Which works absolutely fine (design-wise):
The calendar will handle multiple users:
Now of course, this is just a simple grid and some rectangles. Unfortunately I cannot use any event with rectangles since it is solely a painted component.
I was hoping to get some input here on how I could handle clickable calendar items (like appointments). Putting Panels or UserControls everywhere sounds pretty damn inefficient to me...? Any input will be apreciated!
How do I call the method FlipTextureVertically in MakePhoto ?
My picture currently taken is upside down in unity, and I came across this texture flipping code, but I do not know how to apply it.
Would really appreciate if someone could help me out here!
public static Texture2D FlipTextureVertically(Texture2D original)
{
Texture2D flipped = new Texture2D(original.width, original.height, TextureFormat.ARGB32, false);
int xN = original.width;
int yN = original.height;
for (int i = 0; i < xN; i++)
{
for (int j = 0; j < yN; j++)
{
flipped.SetPixel(i, yN - j - 1, original.GetPixel(i, j));
}
}
flipped.Apply();
return flipped;
}
public string MakePhoto(bool openIt)
{
int resWidth = Screen.width;
int resHeight = Screen.height;
Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); //Create new texture
RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
// hide the info-text, if any
if (infoText)
{
infoText.text = string.Empty;
}
// render background and foreground cameras
if (backroundCamera && backroundCamera.enabled)
{
backroundCamera.targetTexture = rt;
backroundCamera.Render();
backroundCamera.targetTexture = null;
}
if (backroundCamera2 && backroundCamera2.enabled)
{
backroundCamera2.targetTexture = rt;
backroundCamera2.Render();
backroundCamera2.targetTexture = null;
}
if (foreroundCamera && foreroundCamera.enabled)
{
foreroundCamera.targetTexture = rt;
foreroundCamera.Render();
foreroundCamera.targetTexture = null;
}
// get the screenshot
RenderTexture prevActiveTex = RenderTexture.active;
RenderTexture.active = rt;
screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
// clean-up
RenderTexture.active = prevActiveTex;
Destroy(rt);
byte[] btScreenShot = screenShot.EncodeToJPG();
Destroy(screenShot);
// save the screenshot as jpeg file
string sDirName = Application.persistentDataPath + "/Screenshots";
if (!Directory.Exists(sDirName))
Directory.CreateDirectory (sDirName);
string sFileName = sDirName + "/" + string.Format ("{0:F0}", Time.realtimeSinceStartup * 10f) + ".jpg";
File.WriteAllBytes(sFileName, btScreenShot);
Debug.Log("Photo saved to: " + sFileName);
if (infoText)
{
infoText.text = "Saved to: " + sFileName;
}
// open file
if(openIt)
{
System.Diagnostics.Process.Start(sFileName);
}
return sFileName;
}
I don't really see why the screenshot should be upside down but I guess you should call it e.g. after
screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
screenShot = FlipTextureVertically(screenShot);
but there might be more efficient ways of doing that.
E.g. not creating a new Texture2D but instead alter only the pixels in the one you already have like
public static void FlipTextureVertically(Texture2D original)
{
var originalPixels = original.GetPixels();
var newPixels = new Color[originalPixels.Length];
var width = original.width;
var rows = original.height;
for (var x = 0; x < width; x++)
{
for (var y = 0; y < rows; y++)
{
newPixels[x + y * width] = originalPixels[x + (rows - y -1) * width];
}
}
original.SetPixels(newPixels);
original.Apply();
}
public static void FlipTextureHorizontally(Texture2D original)
{
var originalPixels = original.GetPixels();
var newPixels = new Color[originalPixels.Length];
var width = original.width;
var rows = original.height;
for (var x = 0; x < width; x++)
{
for (var y = 0; y < rows; y++)
{
newPixels[x + y * width] = originalPixels[(width - x - 1) + y * width];
}
}
original.SetPixels(newPixels);
original.Apply();
}
and use it like
screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
FlipTextureVertically(screenShot);
The reason your image is flipped is that you are swicthing the vertical pixels in your code.
public static Texture2D FlipTextureVertically(Texture2D original)
{
Texture2D flipped = new Texture2D(original.width, original.height, TextureFormat.ARGB32, false);
int xN = original.width;
int yN = original.height;
for (int i = 0; i < xN; i++)
{
for (int j = 0; j < yN; j++)
{
flipped.SetPixel(i, yN - j - 1, original.GetPixel(i, j));
}
}
flipped.Apply();
return flipped;
}
should be
public static Texture2D FlipTextureVertically(Texture2D original)
{
Texture2D flipped = new Texture2D(original.width, original.height, TextureFormat.ARGB32, false);
int xN = original.width;
int yN = original.height;
for (int i = 0; i < xN; i++)
{
for (int j = 0; j < yN; j++)
{
flipped.SetPixel(xN - i - 1, yN, original.GetPixel(i, j));
}
}
flipped.Apply();
return flipped;
}
I've got function:
private string[] Letters = new string[11] {"", "A", "B", "C", "D", "E","F", "G","H", "I", "J"};
private void GenerateGameMap()
{
int LocA = 5;
int LocB = 5;
for(int i = 1; i < 12; i++)
{
for(int i2 = 1; i2 < 12; i2++)
{
Canvas canvas = new Canvas();
canvas.Width = 26;
canvas.Height = 26;
canvas.Margin = new Thickness(LocA + 1, LocB + 1, 0, 0);
Border border = new Border();
border.BorderThickness = new Thickness(2);
if (i == 1 || i2 == 1)
{
Label label = new Label();
label.FontFamily = new FontFamily("Arial");
label.FontSize = 20;
label.Foreground = Brushes.White;
label.Margin = new Thickness(-1, -2, 0, 0);
label.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
label.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
if(i == 1)
{
if(i2 > 1)
{
label.Content = Litery[i2 - 1];
}
}else
{
if(i2==1)
{
label.Content = (i - 1).ToString();
}
}
border.BorderBrush = Brushes.Gold;
canvas.Background = Brushes.Black;
canvas.Children.Add(label);
}else
{
border.BorderBrush = Brushes.CadetBlue;
canvas.Background = Brushes.BurlyWood;
}
if(i > 1 && i2 > 1 )
{
canvas.Name = Letters[i2 - 1] + (i - 1).ToString();
canvas.MouseLeftButtonUp +=canvas_MouseLeftButtonUp;
}
border.Width = 28;
border.Height = 28;
border.Margin = new Thickness(LocA, LocB, 0, 0);
LocA+=30;
MainGameCanvas.Children.Add(canvas);
MainGameCanvas.Children.Add(border);
if(i2 == 11)
{
LocA = 5;
}
}
LocB += 30;
}
}
Everything is fine with that function. But when I'am trying to find canvas:
private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
string canvasName = Text1.Text + Text2.Text;
var GameObject = MainGameCanvas.FindName(canvasName);
Canvas SelectedGameobject = GameObject as Canvas;
SelectedGameobject.Background = Brushes.YellowGreen;
}
I'am receiving error 'Object reference not set on instance of an object' in line "SelectedGameobject.Background = Brushes.YellowGreen;". Is there other way to find this control ?. As i said, I'am sure that function GenerateGameMap() is working corectly.