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!
Related
I set the points and when the points of the same color form a square, I draw a polygon. But when a new square is formed, the old one disappears.
can you tell me how to make sure that when drawing a new polygon, the old one does not disappear?
in the checkpoint() function, I check whether there is a square of points of the same color and return e coordinates for drawing.
public partial class Form1 : Form
{
private Class1 Class1 = new Class1();
private CellState currentPlayer = CellState.Red;
public const int SIZE = 11;
public const int Icon_Size = 30;
public Form1()
{
InitializeComponent();
}
//ставит точки
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
var p = new Point((int)Math.Round(1f * e.X / Icon_Size), (int)Math.Round(1f * e.Y / Icon_Size));
if (Class1[p] == CellState.Empty)
{
Class1.SetPoint(p, currentPlayer);
currentPlayer = Class1.Inverse(currentPlayer);
Invalidate();
}
}
//рисуем
private void OnPaint(object sender, PaintEventArgs e)
{
e.Graphics.ScaleTransform(Icon_Size, Icon_Size);
//рисуем сеточку
using (var pen = new Pen(Color.Gainsboro, 0.1f))
{
for (int x = 1; x < SIZE; x++)
e.Graphics.DrawLine(pen, x, 1, x, SIZE - 1);
for (int y = 1; y < SIZE; y++)
e.Graphics.DrawLine(pen, 1, y, SIZE - 1, y);
}
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//рисуем точки
using (var brush = new SolidBrush(Color.White))
for (int x = 1; x < Form1.SIZE; x++)
for (int y = 1; y < Form1.SIZE; y++)
{
var p = new Point(x, y);
var cell = Class1[p];
if (cell != CellState.Empty)
{
brush.Color = StateToColor(cell);
e.Graphics.FillEllipse(brush, x - 0.2f, y - 0.2f, 0.4f, 0.4f);
}
}
using (var PenP = new Pen(Color.Black, 0.1f))
using (var brush = new SolidBrush(Color.White))
{
Class1.CheckPoint();
int i = Class1.CheckPoint()[0];
int j = Class1.CheckPoint()[1];
int cp = Class1.CheckPoint()[2];
if (cp == 1)
{
PenP.Color = Color.Red;
brush.Color = Color.IndianRed;
Point[] a = { new Point(i, j), new Point(i + 1, j), new Point(i + 1, j + 1), new Point(i, j + 1) };
e.Graphics.FillPolygon(brush, a);
e.Graphics.DrawPolygon(PenP, a);
}
if (cp == 2)
{
PenP.Color = Color.Blue;
brush.Color = Color.RoyalBlue;
Point[] a = { new Point(i, j), new Point(i + 1, j), new Point(i + 1, j + 1), new Point(i, j + 1) };
e.Graphics.FillPolygon(brush, a);
e.Graphics.DrawPolygon(PenP, a);
}
}
}
//условие смены цвета под ход игрока
Color StateToColor(CellState state, byte alpha = 255)
{
var res = state == CellState.Blue ? Color.Blue : Color.Red;
return Color.FromArgb(alpha, res);
}
}
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);
}
When I run this code
Bitmap im = new Bitmap(600, 600, PixelFormat.Format16bppGrayScale);
int height = im.Height;
int width = im.Width;
Point p1 = new Point(0, 0);
Point p2 = new Point(im.Size.Width, 0);
Point p3 = new Point(im.Width / 2, im.Height);
Random r = new Random();
Point p = new Point(r.Next(0, im.Size.Width), r.Next(0, im.Size.Height));
BitmapData data = im.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format16bppGrayScale);
const int stride = 2;
int wsrtide = data.Stride;
unsafe
{
IntPtr osc0 = data.Scan0;
ushort* sc0 = (ushort*)data.Scan0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
*sc0 = 0;
sc0 += 1;
}
}
for (long i = 0; i < width * height; i++)
{
if (i % 1_000_000 == 0)
{
Console.WriteLine(i);
}
var ran = r.Next(0, 3);
Point tp;
switch (ran)
{
case 0:
tp = new Point((p1.X + p.X) / 2, (p1.Y + p.Y) / 2);
sc0 = (ushort*)((int)osc0 + (wsrtide * tp.Y + (tp.X * stride)));
*sc0 = ushort.MaxValue;
p = tp;
break;
case 1:
tp = new Point((p2.X + p.X) / 2, (p2.Y + p.Y) / 2);
sc0 = (ushort*)((int)osc0 + (wsrtide * tp.Y + (tp.X * stride)));
*sc0 = ushort.MaxValue;
p = tp;
break;
case 2:
tp = new Point((p3.X + p.X) / 2, (p3.Y + p.Y) / 2);
sc0 = (ushort*)((int)osc0 + (wsrtide * tp.Y + (tp.X * stride)));
*sc0 = ushort.MaxValue;
p = tp;
break;
}
}
im.UnlockBits(data);
im.Save(Environment.CurrentDirectory + "\\img.png");
im.Dispose();
It throws where I save the bitmap
System.Runtime.InteropServices.ExternalException: A generic error
occurred in GDI+.`
I am almost certain that this isn't caused by file permissions, when I give the program admin permission and delete the image to reset permissions it still throws. I can confirm that this code swapped with BitmapSetPixel() on RGB works.
My suspicion is that I'm messing up the pointers, but I'm not really sure. Also, curiously enough, it makes empty png files even though it throws.
The purpose of this code is to generate a Sierpinski triangle using the chaos game method.
Your problem is the Format16bppGrayScale i don't think the GDI supports it very well.
Basically if you just create the Bitmap in Format16bppGrayScale, and save it with nothing else, it still gives the error.
I have taken the liberty to rewrite your method Format32bppPArgb
private unsafe static void Main(string[] args)
{
var height = 600;
var width = 600;
var p1 = new Point(0, 0);
var p2 = new Point(width, 0);
var p3 = new Point(width / 2, height);
var r = new Random();
var p = new Point(r.Next(0, width), r.Next(0, width));
using (var im = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
{
var data = im.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
var sc0 = (int*)data.Scan0;
var pLen = sc0 + height * width;
var black = Color.Black.ToArgb();
var white = Color.White.ToArgb();
for (var pI = sc0; pI < pLen; pI++)
*pI = black;
for (long i = 0; i < width * height; i++)
{
Point tp;
switch (r.Next(0, 3))
{
case 0:
tp = new Point((p1.X + p.X) / 2, (p1.Y + p.Y) / 2);
*(sc0 + tp.Y + tp.X * width) = white;
p = tp;
break;
case 1:
tp = new Point((p2.X + p.X) / 2, (p2.Y + p.Y) / 2);
*(sc0 + tp.Y + tp.X * width) = white;
p = tp;
break;
case 2:
tp = new Point((p3.X + p.X) / 2, (p3.Y + p.Y) / 2);
*(sc0 + tp.Y + tp.X * width) = white;
p = tp;
break;
}
}
im.UnlockBits(data);
im.Save(#"D:\img.png", ImageFormat.Png);
}
}
Result
You can convert it after the fact if you want, add pepper and salt to taste
Also if you get rid of all the points and cache the colors this will be a bit faster
So question is why I'm always getting black rectangle when save my Bitmap like this
myBitmap.Save(Path.GetDirectoryName(myFilePath)+"\\temp.bmp",System.Drawing.Imaging.ImageFormat.Bmp);
What is wrong in this?
UPD
Here is how i'm getting my Bitmap. Actually it is a post Barcode in "Interleaved 2 of 5" format
Image barcodeImage = new System.Drawing.Bitmap(mImgWidth == 0 ? DEFAULT_WIDTH : mImgWidth, mImgHeight == 0 ? DEFAULT_HEIGHT : mImgHeight);
using (Graphics gr = Graphics.FromImage(barcodeImage))
{
int textStartPosX = (int)((float)BARCODE_TEXT_LEFT_MARGIN * mScaleRatioW);
int textStartPosY = (int)((float)BARCODE_TEXT_TOP_MARGIN * mScaleRatioH);
int textRectWidth = (int)((float)BARCODE_TEXT_WIDTH * mScaleRatioW);
int textRextHeight = (int)((float)BARCODE_TEXT_HEIGHT * mScaleRatioH);
//float textSize = DEFAULT_TEXT_SIZE + DEFAULT_TEXT_SIZE;
RectangleF textRect = new RectangleF(textStartPosX, textStartPosY, textRectWidth, textRextHeight);
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawString(RUSSIAN_POST, new Font("Helvetica", 7), Brushes.Black, textRect);
int barCodeStartPosX = (int)(((float)BARCODE_LEFT_MARGIN) * mScaleRatioW);
int barCodeTopMargin = (int)(((float)BARCODE_TOP_MARGIN) * mScaleRatioH);
int barCodeHeight = (int)((float)BARCODE_HEIGHT * mScaleRatioH);
for (int codeidx = 0; codeidx < barcodeString.Length; codeidx++)
{
char code = barcodeString[codeidx];
int barwidth = ((code == 'N') || (code == 'n')) ? (int)((float)1 * mScaleRatioW) : (int)((float)3 * mScaleRatioW);
if ((code == 'N') || (code == 'W'))
{
gr.FillRectangle(System.Drawing.Brushes.Black, barCodeStartPosX, barCodeTopMargin, barwidth, barCodeHeight);
}
barCodeStartPosX += barwidth;
}
int numStartPosX = (int)(((float)BARCODE_NUM_LEFT_MARGIN) * mScaleRatioW);
int numStartPosY = (int)((float)BARCODE_NUM_TOP_MARGIN * mScaleRatioH);
int numRectWidth = (int)((float)BARCODE_NUM_WIDTH * mScaleRatioW);
int numRextHeight = (int)((float)BARCODE_NUM_HEIGHT * mScaleRatioH);
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
RectangleF barCodeNumRect = new RectangleF();
for (int i = 0; i < 4; i++) {
float startX;
switch (i) {
case 0: barCodeNumRect = new RectangleF(numStartPosX, numStartPosY, numRectWidth, numRextHeight);
gr.DrawString(barcodeNumber.Substring(0,6), new Font("Helvetica", 7), Brushes.Black, barCodeNumRect);
break;
case 1:
numStartPosX = (int)( (numStartPosX + BARCODE_NUM_MONTH_LEFT_PADDING) * mScaleRatioW);
barCodeNumRect = new RectangleF(numStartPosX, numStartPosY, numRectWidth, numRextHeight);
gr.DrawString(barcodeNumber.Substring(6, 2), new Font("Helvetica", 7), Brushes.Black, barCodeNumRect);
break;
case 2:
numStartPosX = (int)((numStartPosX + BARCODE_NUM_VALUE_LEFT_PADDING) * mScaleRatioW);
barCodeNumRect = new RectangleF(numStartPosX, numStartPosY, numRectWidth, numRextHeight);
gr.DrawString(barcodeNumber.Substring(8, 5), new Font("Helvetica", 7, FontStyle.Bold), Brushes.Black, barCodeNumRect);
break;
case 3:
numStartPosX = (int)((numStartPosX + BARCODE_NUM_CHECKDIGIT_LEFT_PADDING) * mScaleRatioW);
barCodeNumRect = new RectangleF(numStartPosX * mScaleRatioW, numStartPosY, numRectWidth, numRextHeight);
gr.DrawString(barcodeNumber.Substring(13, 1), new Font("Helvetica", 7), Brushes.Black, barCodeNumRect);
break;
default: break;
}
}
}
UPD 2
Have no problems when I save it without System.Drawing.Imaging.ImageFormat.Bmp
try to save using this way:
WriteableBitmap eb = new WriteableBitmap(bitmapImage);
MemoryStream memoryStream1 = new MemoryStream();
eb.SaveJpeg(memoryStream1, bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
memoryStream1.Seek(0, SeekOrigin.Begin);
MediaLibrary library1 = new MediaLibrary();
string filename1 = "SavedPicture_" + DateTime.Now.ToString("y_M_d_H_m_s");
Picture pic1 = library1.SavePicture(filename1, memoryStream1);
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