I created an animated image to move on my canvas then I created another animated image ;
I want to hide just my first image after it's movement and before moving another;
I tried to set opacity of my drawing visual or image brush or etc zero;but all of my image
hide;
List<EllipseGeometry> eg = new List<EllipseGeometry>();
Path ballPath;
int c = 0;
foreach (Polyline p in pl)
{
if (p.Points.Count > 1)
{
ballPath = new Path();
FormattedText formattedText = new FormattedText(" " + (anl[c].DOffset).ToString() + "\n " + anl[c].playername + " ", CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("arial"),
20,
Brushes.Black);
formattedText.MaxTextWidth = 500;
formattedText.MaxTextHeight = 500;
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawImage(il[c].Source, new Rect(4, 0, 26, 26));//30
drawingContext.DrawText(formattedText, new Point(1, 2));
drawingContext.Close();
RenderTargetBitmap bmp = new RenderTargetBitmap((int)formattedText.WidthIncludingTrailingWhitespace, (int)formattedText.Height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
ImageBrush b = new ImageBrush(bmp);
b.Stretch = Stretch.Uniform;
ballPath.Fill = b;
mainwindow.animecan.Children.Add(ballPath);
////
int jy = 0;
for (int i = 0; i < anl.Count; i++)
{
try
{
if (anl[i].offset == m)
jy = anl[i].offset;
}
catch
{
}
}
if (multi && p.Uid == jy.ToString())//اگر آفست مالتی اسپید شده باشه
{
eg.Add(new EllipseGeometry(ms[ih].p1, 27, 27));
ballPath.Data = eg.First();// animatedEllipseGeometry;
PathFigure myPathFigure = new PathFigure();
PointCollection pe = new PointCollection();
pe.Add(ms[ih].p1);
pe.Add(ms[ih].p2);
myPathFigure.StartPoint = eg.First().Center;
myPathFigure.Segments.Add(
new PolyLineSegment(pe, true));
PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);
myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);//
PointAnimationUsingPath centerPointAnimation1 = new PointAnimationUsingPath();
centerPointAnimation1.PathGeometry = myPathGeometry;
centerPointAnimation1.Duration = TimeSpan.FromSeconds(ms[ih].sspeed);
centerPointAnimation1.BeginTime = TimeSpan.FromSeconds(ms[ih].delay);
centerPointAnimation1.FillBehavior = FillBehavior.HoldEnd;
eg.First().BeginAnimation(EllipseGeometry.CenterProperty, centerPointAnimation1);
eg.Remove(eg.First());
}
c++;
I believe that your problem is caused because your whole code block is executed 'at once' (before updating the UI), rather than 'line by line'. In order to make your call to the Visibility property update before execution reaches the end of the code block, you'll need to queue it on the Dispatcher object. Try this:
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
{
yourControl.Visibility = Visibility.Collapsed;
});
Related
I get the following error on a Zebra tablet t55 when running my app:
Unhandled exception at 0x00007FFEA4A22D45 (Windows.UI.Xaml.dll) in PerfectDelivery.exe: 0xC000041D: An unhandled exception was encountered during a user callback.
It happens after I load all my sqlite database and run the app the first time. After the crash I start the app back up again and it runs fine. The offending Combobox is here:
private void InitProducts()
{
StpProducts.Children.Clear();
_lstItemsInMultipleCrates = new List<int>();
Invoice deliveryDetails = new Invoice(((App)Application.Current).OrderId);
ItemsInCrate = new List<InvoiceItem>();
if (_selectedCrate != null)
{
btnFinishCrate.Visibility = Visibility.Visible;
foreach (InvoiceItem i in deliveryDetails.InvoiceItems.Where(
x => x.CrateNumber.CrateId == _selectedCrate))
{
ItemsInCrate.Add(i);
GridProducts = new Grid();
GridProducts.Height = 35;
GridProducts.Width = 600;
GridProducts.HorizontalAlignment = HorizontalAlignment.Left;
ColumnDefinition cdProductName = new ColumnDefinition();
cdProductName.Width = new GridLength(170, GridUnitType.Star);
ColumnDefinition cdQty = new ColumnDefinition();
cdQty.Width = new GridLength(45, GridUnitType.Star);
ColumnDefinition cdUnits = new ColumnDefinition();
cdUnits.Width = new GridLength(60, GridUnitType.Star);
ColumnDefinition cdChecked = new ColumnDefinition();
cdChecked.Width = new GridLength(30, GridUnitType.Star);
ColumnDefinition cdDropdown = new ColumnDefinition();
cdDropdown.Width = new GridLength(80, GridUnitType.Star);
ColumnDefinition cdFiller = new ColumnDefinition();
cdFiller.Width = new GridLength(1, GridUnitType.Star);
RowDefinition row = new RowDefinition();
row.Height = new GridLength(35, GridUnitType.Star);
GridProducts.ColumnDefinitions.Add(cdProductName);
GridProducts.ColumnDefinitions.Add(cdQty);
GridProducts.ColumnDefinitions.Add(cdUnits);
GridProducts.ColumnDefinitions.Add(cdChecked);
GridProducts.ColumnDefinitions.Add(cdDropdown);
TextBlock txbOrderDetailPickedId = new TextBlock { Name = "ODPID" };
txbOrderDetailPickedId.Text = i.OrderDetailPickedId.ToString("G");
txbOrderDetailPickedId.Visibility = Visibility.Collapsed;
TextBlock txbOriginalQty = new TextBlock { Name = "OQ" };
txbOriginalQty.Text = i.Quantity.ToString("N");
txbOriginalQty.Visibility = Visibility.Collapsed;
List<long?> lstCrateCount = new List<long?>();
foreach (InvoiceItem crateCount in deliveryDetails.InvoiceItems.Where(x => x.CrateNumber.OrderDetailPickedId == i.OrderDetailPickedId))
{
lstCrateCount.Add(crateCount.CrateNumber.CrateId);
}// return count of crates for item. If > 1 display crate number(s)
TextBlock txbProductName = new TextBlock();
TextBox txbQuantity = new TextBox();
txbQuantity.Text = i.Quantity.ToString("N");
txbQuantity.Height = 35;
InputScope scope = new InputScope();
InputScopeName scopeName = new InputScopeName { NameValue = InputScopeNameValue.Number };
scope.Names.Add(scopeName);
txbQuantity.InputScope = scope;
TextBlock txbUnits = new TextBlock();
txbUnits.Text = i.PackDescription;
txbUnits.HorizontalTextAlignment = TextAlignment.Center;
txbUnits.VerticalAlignment = VerticalAlignment.Center;
CheckBox chkChecked = new CheckBox();
---> CmbDiscrepancies = new ComboBox{ SelectedIndex = -1};
if (CmbDiscrepancies?.Items != null)
{
CmbDiscrepancies.Items.Add("Correct");
CmbDiscrepancies.Items.Add("Damaged");
CmbDiscrepancies.Items.Add("Missing");
CmbDiscrepancies.Items.Add("Wrong Item");
CmbDiscrepancies.Items.Add("Out of Stock");
CmbDiscrepancies.Items.Add("Incorrect Amt");
}
CmbDiscrepancies.SelectedIndex = 0;
CmbDiscrepancies.VerticalAlignment = VerticalAlignment.Center;*
if (lstCrateCount.Count == 1)
{
txbProductName.Text = i.ProductName;
}
else if (!Crate.ItemInMultipleCrates(i.OrderDetailPickedId))
{
_lstItemsInMultipleCrates.Add(i.OrderDetailPickedId);
txbProductName.TextWrapping = TextWrapping.Wrap;
txbProductName.Text = i.ProductName + "\r\n" + "(";
int count = 0;
foreach (long? crate in lstCrateCount)
{
count++;
txbProductName.Text += count != lstCrateCount.Count ? crate + ", " : crate + ")\r\nQty is the total in all crates listed above.";
}
GridProducts.Height = 50 * (lstCrateCount.Count * .66);
row.Height = new GridLength(GridProducts.Height, GridUnitType.Pixel);
}
if (Crate.ItemInMultipleCrates(i.OrderDetailPickedId))
{
txbProductName.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
CmbDiscrepancies.IsEnabled = false;
txbQuantity.IsEnabled = false;
if (_lstItemsInMultipleCrates.Count > 0)
GridProducts.Height = 35 * (_lstItemsInMultipleCrates.Count * 1.32);
else
{
GridProducts.Height = 35 * 1.32;
}
row.Height = new GridLength(GridProducts.Height, GridUnitType.Pixel);
txbProductName.Text = i.ProductName + "\r\n" + "(Item is in multiple crates)";
chkChecked.IsChecked = true;
chkChecked.IsEnabled = false;
}
GridProducts.Children.Add(txbOriginalQty);
GridProducts.Children.Add(txbOrderDetailPickedId);
GridProducts.Children.Add(txbProductName);
GridProducts.Children.Add(txbQuantity);
GridProducts.Children.Add(txbUnits);
GridProducts.Children.Add(chkChecked);
GridProducts.Children.Add(CmbDiscrepancies);
Grid.SetColumn(txbProductName, 0);
Grid.SetColumn(txbQuantity, 1);
Grid.SetColumn(txbUnits, 2);
Grid.SetColumn(chkChecked, 3);
Grid.SetColumn(CmbDiscrepancies, 4);
Grid.SetRow(txbProductName, 0);
Grid.SetRow(txbQuantity, 0);
Grid.SetRow(txbUnits, 0);
Grid.SetRow(chkChecked, 0);
Grid.SetRow(CmbDiscrepancies, 0);
GridProducts.RowDefinitions.Add(row);
StpProducts.Children.Add(GridProducts);
}
}
The XAML is
<ScrollViewer x:Name="ScvProducts" HorizontalAlignment="Left" Height="354" Margin="375,146,0,0" VerticalAlignment="Top" Width="638" BorderBrush="#FF1B933C" BorderThickness="2" >
<StackPanel x:Name="StpProducts" MinHeight="450" Width="612" HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Vertical" Height="995" >
<Grid x:Name="GridProducts">
<ComboBox x:Name="CmbDiscrepancies" Visibility></ComboBox>
</Grid>
</StackPanel>
</ScrollViewer>
Upgrading from Windows 10 1709 to 1803 fixed the existing code. I also got rid of the stack panel and add the row definitions dynamically which seems to have addressed the 1709 version.
We have 3D models in WPF and use a cursor made from a Canvas and some internal parts. We turn the HW cursor off and move the Canvas through MouseEvent. The issue is that there are terrible artifacts on the screen as you move from left to right (not nearly as bad right to left). I have played with snaptodevicepixels, Edge mode and nvidea AA settings but the only thing that "fixes" is setting edge mode to aliased for the 3dviewport - and we don't want that. I have even made the cursor completely transparent and it still leaves artifacts.
I broke out some of the code for demonstration. You can especially see the artifacts moving upper-left to lower-right.
Anyone think they can help me out here? I'm head banging and not in a good way. It's looking more like a bug in the AA code.
Thanks
T
FYI: I used some Petzold code here for the beach ball.
Bad AA BeachBall
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;
namespace Cursoraa2
{
class Program : Window
{
[STAThread]
public static void Main() => new Application().Run(new Program());
public Program()
{
Width = 500;
Height = 500;
var grid = new Grid();
var viewport = new Viewport3D();
grid.Children.Add(viewport);
Content = grid;
//RenderOptions.SetEdgeMode(viewport,EdgeMode.Aliased);
DynamicCurosr.Start(grid, grid, 40, Color.FromArgb(40, 0x33, 0x33, 0xff), Colors.Blue);
MouseMove += MainWindow_MouseMove;
MakeBeachBallSphere(viewport);
}
private void MainWindow_MouseMove(object sender, MouseEventArgs e) => DynamicCurosr.Move(e.GetPosition(this));
public void MakeBeachBallSphere(Viewport3D viewport)
{
// Get the MeshGeometry3D from the GenerateSphere method.
var mesh = GenerateSphere(new Point3D(0, 0, 0), 1, 36, 18);
mesh.Freeze();
// Define a brush for the sphere.
var brushes = new Brush[6] { Brushes.Red, Brushes.Blue,
Brushes.Yellow, Brushes.Orange,
Brushes.White, Brushes.Green };
var drawgrp = new DrawingGroup();
for (var i = 0; i < brushes.Length; i++)
{
var rectgeo = new RectangleGeometry(new Rect(10 * i, 0, 10, 60));
var geodraw = new GeometryDrawing(brushes[i], null, rectgeo);
drawgrp.Children.Add(geodraw);
}
var drawbrsh = new DrawingBrush(drawgrp);
drawbrsh.Freeze();
// Define the GeometryModel3D.
var geomod = new GeometryModel3D
{
Geometry = mesh,
Material = new DiffuseMaterial(drawbrsh)
};
// Create a ModelVisual3D for the GeometryModel3D.
var modvis = new ModelVisual3D { Content = geomod };
viewport.Children.Add(modvis);
// Create another ModelVisual3D for light.
var modgrp = new Model3DGroup();
modgrp.Children.Add(new AmbientLight(Color.FromRgb(128, 128, 128)));
modgrp.Children.Add(new DirectionalLight(Color.FromRgb(128, 128, 128), new Vector3D(2, -3, -1)));
modvis = new ModelVisual3D {Content = modgrp};
viewport.Children.Add(modvis);
// Create the camera.
var cam = new PerspectiveCamera(new Point3D(0, 0, 8), new Vector3D(0, 0, -1), new Vector3D(0, 1, 0), 45);
viewport.Camera = cam;
// Create a transform for the GeometryModel3D.
var axisangle = new AxisAngleRotation3D(new Vector3D(1, 1, 0), 180);
var rotate = new RotateTransform3D(axisangle);
geomod.Transform = rotate;
// Animate the RotateTransform3D.
//DoubleAnimation anima = new DoubleAnimation(360, new Duration(TimeSpan.FromSeconds(5)));
//anima.RepeatBehavior = RepeatBehavior.Forever;
//axisangle.BeginAnimation(AxisAngleRotation3D.AngleProperty, anima);
}
MeshGeometry3D GenerateSphere(Point3D center, double radius, int slices, int stacks)
{
// Create the MeshGeometry3D.
var mesh = new MeshGeometry3D();
// Fill the Position, Normals, and TextureCoordinates collections.
for (var stack = 0; stack <= stacks; stack++)
{
var phi = Math.PI / 2 - stack * Math.PI / stacks;
var y = radius * Math.Sin(phi);
var scale = -radius * Math.Cos(phi);
for (var slice = 0; slice <= slices; slice++)
{
var theta = slice * 2 * Math.PI / slices;
var x = scale * Math.Sin(theta);
var z = scale * Math.Cos(theta);
var normal = new Vector3D(x, y, z);
mesh.Normals.Add(normal);
mesh.Positions.Add(normal + center);
mesh.TextureCoordinates.Add(
new Point((double)slice / slices,
(double)stack / stacks));
}
}
// Fill the TriangleIndices collection.
for (var stack = 0; stack < stacks; stack++)
for (var slice = 0; slice < slices; slice++)
{
var n = slices + 1; // Keep the line length down.
if (stack != 0)
{
mesh.TriangleIndices.Add((stack + 0) * n + slice);
mesh.TriangleIndices.Add((stack + 1) * n + slice);
mesh.TriangleIndices.Add((stack + 0) * n + slice + 1);
}
if (stack != stacks - 1)
{
mesh.TriangleIndices.Add((stack + 0) * n + slice + 1);
mesh.TriangleIndices.Add((stack + 1) * n + slice);
mesh.TriangleIndices.Add((stack + 1) * n + slice + 1);
}
}
return mesh;
}
}
public static class DynamicCurosr
{
static public bool InSession { get; private set; }
private static Panel theCursor;
private static readonly ScaleTransform ScaleTransform = new ScaleTransform(1, 1);
private static readonly MatrixTransform MatrixTransform = new MatrixTransform(1, 0, 0, 1, 0, 0);
private static Color defaultFill = Color.FromArgb(20, 255, 255, 255);
private static Color fillFromUser;
private static double strokeFromUser = 0;
private static Color strokeColorFromUser = Colors.Black;
private static int centerDotSizeFromUser = 10; // need to get from user
private static double initialDiameter = double.NaN;
private static Panel cursorPanel;
private static Panel mousePanel;
public static bool Start(Panel cursorPanelIn, Panel mousePanelIn, double radius)
{
return Start(cursorPanelIn, mousePanelIn, radius, defaultFill);
}
public static bool Start(Panel cursorPanelIn, Panel mousePanelIn, double radius, Color fill, Color strokeColor = default(Color), double strokeSize = .16)
{
strokeColor = strokeColor == default(Color) ? Colors.Black : strokeColor;
strokeColorFromUser = strokeColor;
fillFromUser = fill;
strokeFromUser = strokeColor == default(Color) ? 0 : strokeSize;
initialDiameter = double.IsNaN(initialDiameter) ? radius * 2 : initialDiameter;
return Start(cursorPanelIn, mousePanelIn);
}
private static bool Start(Panel cursorPanelIn, Panel mousePanelIn)
{
if (InSession) return false;
cursorPanel = cursorPanelIn;
mousePanel = mousePanelIn;
var point = Mouse.GetPosition(cursorPanel);
theCursor = MakeACursor(theCursor, initialDiameter / 2);
InSession = true;
cursorPanel.Cursor = Cursors.None;
theCursor.Visibility = Visibility.Visible;
Move(point);
if (cursorPanel.Children.Contains(theCursor))
return false;
cursorPanel.Children.Add(theCursor);
Mouse.OverrideCursor = Cursors.None;
return true;
}
public static void Stop()
{
if (InSession)
{
Mouse.OverrideCursor = null;
theCursor.Visibility = Visibility.Collapsed;
cursorPanel.Children.Remove(theCursor);
InSession = false;
}
}
public static void Move(Point point)
{
if (InSession && theCursor.Visibility == Visibility.Visible)
{
var m = MatrixTransform.Matrix;
m.OffsetX = point.X - theCursor.Width / 2;
m.OffsetY = point.Y - theCursor.Height / 2;
MatrixTransform.Matrix = m;
theCursor.RenderTransform = MatrixTransform;
}
}
public static Panel MakeACursor(Panel theCursor, double radius, Color fillColorIn = default(Color), Color strokeColorIn = default(Color))
{
var strokeColor = new SolidColorBrush(strokeColorIn == default(Color) ? strokeColorFromUser : strokeColorIn);
if (theCursor == null)
{
theCursor = new Grid()
{
Width = radius * 2,
Height = radius * 2,
Background = null,
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
RenderTransform = ScaleTransform,
RenderTransformOrigin = new Point(.5, .5),
};
var cursorElement = new Ellipse
{
Width = radius * 2,
Height = radius * 2,
Fill = new SolidColorBrush(fillColorIn == default(Color) ? fillFromUser : fillColorIn),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
StrokeThickness = strokeFromUser,
Stroke = strokeColor,
RenderTransformOrigin = new Point(.5, .5)
};
theCursor.Children.Add(cursorElement);
}
MakeCursorOverlay(theCursor, radius, strokeColor);
return theCursor;
}
public static void MakeCursorOverlay(Panel theCursor, double radius, SolidColorBrush strokeColor)
{
var save = theCursor.Children[0];
theCursor.Children.Clear();
theCursor.Children.Add(save);
var circle = new Ellipse
{
Width = centerDotSizeFromUser,
Height = centerDotSizeFromUser,
Fill = null,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
StrokeThickness = strokeFromUser,
Stroke = strokeColor,
RenderTransformOrigin = new Point(.5, .5)
};
theCursor.Children.Add(circle);
}
}
}
I am calling a method that has a Grid.Children.Clear() functionality. When calling it from different methods it works well. But when I call my the method from an xmpp_onmessage method. I am experiencing an error. “The calling thread cannot access this object because a different thread owns it.”
Here is the method that containts Grid.Children.Clear()the :
private void ConstructChatView(Boolean isChat)
{
System.Uri resourceUri = new System.Uri("Public/Images/chat_green-textarea.png", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
System.Uri resourceUri2 = new System.Uri("Public/Images/chat_green-textarea-tail.png", UriKind.Relative);
StreamResourceInfo streamInfo2 = Application.GetResourceStream(resourceUri2);
System.Uri resourceUri3 = new System.Uri("Public/Images/chat_blue-textarea.png", UriKind.Relative);
StreamResourceInfo streamInfo3 = Application.GetResourceStream(resourceUri3);
System.Uri resourceUri4 = new System.Uri("Public/Images/chat_blue-textarea-tail.png", UriKind.Relative);
StreamResourceInfo streamInfo4 = Application.GetResourceStream(resourceUri4);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp;
BitmapFrame temp2 = BitmapFrame.Create(streamInfo2.Stream);
BitmapFrame temp3 = BitmapFrame.Create(streamInfo3.Stream);
var brush2 = new ImageBrush();
brush2.ImageSource = temp3;
BitmapFrame temp4 = BitmapFrame.Create(streamInfo4.Stream);
int ctr = 0;
chatGrid.Children.Clear();
if (isChat == true)
{
for (int i = 0; i < _messageView.Count; i++)
{
if ((!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
{
RowDefinition chatGridRow1 = new RowDefinition();
RowDefinition chatGridRow2 = new RowDefinition();
RowDefinition chatGridRow3 = new RowDefinition();
chatGrid.RowDefinitions.Add(chatGridRow1);
chatGrid.RowDefinitions.Add(chatGridRow2);
chatGrid.RowDefinitions.Add(chatGridRow3);
if (_messageView.ElementAt(i).IsMe == true)
{
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Right;
Message.Margin = new Thickness(0, 0, 5, 0);
Message.Background = brush2;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Bluetail = new Image();
Bluetail.Source = temp4;
Bluetail.HorizontalAlignment = HorizontalAlignment.Right;
Bluetail.Height = 10;
Bluetail.Width = 20;
Bluetail.Margin = new Thickness(0, -(0.7), 10, 0);
Grid.SetRow(Bluetail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.HorizontalAlignment = HorizontalAlignment.Right;
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Bluetail);
chatGrid.Children.Add(Sender);
}
else
{
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Left;
Message.Margin = new Thickness(5, 0, 0, 0);
Message.Background = brush;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Greentail = new Image();
Greentail.Source = temp2;
Greentail.HorizontalAlignment = HorizontalAlignment.Left;
Greentail.Height = 10;
Greentail.Width = 20;
Greentail.Margin = new Thickness(10, -(0.7), 5, 0);
Grid.SetRow(Greentail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.HorizontalAlignment = HorizontalAlignment.Left;
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Greentail);
chatGrid.Children.Add(Sender);
}
}
}
}
else
{
for (int i = 0; i < _messageView.Count; i++)
{
if (_messageView.ElementAt(i).IsMe == true && (!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
{
RowDefinition chatGridRow1 = new RowDefinition();
RowDefinition chatGridRow2 = new RowDefinition();
RowDefinition chatGridRow3 = new RowDefinition();
chatGrid.RowDefinitions.Add(chatGridRow1);
chatGrid.RowDefinitions.Add(chatGridRow2);
chatGrid.RowDefinitions.Add(chatGridRow3);
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Margin = new Thickness(0, 10, 300, 0);
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Left;
Message.Background = brush;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Greentail = new Image();
Greentail.Source = temp2;
Greentail.HorizontalAlignment = HorizontalAlignment.Left;
Greentail.Height = 10;
Greentail.Width = 20;
Greentail.Margin = new Thickness(5, -(0.7), 0, 0);
Grid.SetRow(Greentail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Greentail);
chatGrid.Children.Add(Sender);
}
}
}
//for (int i = 0; i < _messageView.Count; i++)
//{
// if (_messageView.ElementAt(i).IsMe == true && (!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
// {
// }
//}
ctr = 0;
scrollView.ScrollToEnd();
}
Any ideas? thanks
Most UI elements may only be modified in the UI thread. As your event handler is apparently invoked in a different thread, you have to use the Dispatcher to invoke your code in the UI thread.
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() => chatGrid.Children.Clear()));
}
EDIT: You may also pass more code to the Invoke call by using an anonymous method:
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() =>
{
// more code here
}));
}
Of course you may also put a bunch of code in another method and pass that to the Invoke call:
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() => ConstructChatViewInUI(isChat)));
}
private void ConstructChatViewInUI(Boolean isChat)
{
...
}
I am new learner to WPF. here I got a question.
I have a image, width:360, height:360. Here I want to crop this image like below:
( 0,0 ) to (120,120) save to the first ImageSource object,
(120,0 ) to (240,120) save to the second ImageSource object,
(240,0 ) to (360,120) save to the third ImageSource object;,
……
pls see more details in below picture:
My code sample below:
private void CutImage(string img)
{
int iLeft = 0;
int iTop = 0;
int count = 0;
Image thisImg = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(img, UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
thisImg.Source = src;
for (int i = 0; i < 3; i++)
{
iTop = i * 120;
for (int j = 0; j < 3; j++)
{
iLeft = j * 120;
Canvas canvas = new Canvas();
Rectangle destRect = new Rectangle();
destRect.SetValue(Canvas.LeftProperty, (double)0);
destRect.SetValue(Canvas.TopProperty,(double)0);
destRect.Width = destRect.Height = 120;
Rect srcRect = new Rect();
srcRect.X = iLeft;
srcRect.Y = iTop;
srcRect.Width = srcRect.Height = 120;
thisImg.Clip = new RectangleGeometry(srcRect);
thisImg.Clip.SetValue(Canvas.TopProperty, (double)iTop);
thisImg.Clip.SetValue(Canvas.LeftProperty, (double)iLeft);
thisImg.Clip.SetValue(Canvas.WidthProperty, (double)120);
thisImg.Clip.SetValue(Canvas.HeightProperty,(double)120);
objImg[count++] = (ImageSource)thisImg.GetValue(Image.SourceProperty);
}
}
}
but it doesn't work as I expected, seems that all the ImageSource objects store the same image, not the corping part. Any one can help me ? thx.
Use CroppedBitmap to do this:
private 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));
}
Just do:
private static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY)
{
if (target == null)
{
return null;
}
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
(int)(bounds.Height * dpiY / 96.0),
dpiX,
dpiY,
PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
}
rtb.Render(dv);
return rtb;
}
VisualBrush part1 = new VisualBrush(yourVISUAL);
part1.ViewBoxUnits = ..Absolute;
part1.ViewBox = new Rect(x, y, width, height);
BitmapSource bitmapSource = CaptureScreen(part1, 96, 96);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(fileStream);
}
I want to create a new blank image of size 100x100.
Paint it in red and save the image as 'test.png'.
Can I access/change the pixel values of the created image.
How can I do it in WPF.
You can use a WritableBitmap for that, then you can use a BitmapEncoder to encode the image and save it.
var bitmap = new WriteableBitmap(100, 100, 96, 96, PixelFormats.Pbgra32, null);
var rect = new Int32Rect(0, 0, 100, 100);
var channelCount = 4;
var pixels = new byte[100 * 100 * channelCount];
for (int i = 0; i < 100 * 100 * channelCount; i+=channelCount)
{
pixels[i + 2] = (byte)255; // Set red channel
pixels[i + 3] = (byte)255; // Set alpha channel
}
bitmap.WritePixels(rect, pixels, channelCount * 100, 0);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (var stream = new FileStream(#"C:\Users\Public\Test.png", FileMode.Create))
{
encoder.Save(stream);
}
If you wanna uses Shapes instead you can do this
var rtb = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32);
var rectangle = new Rectangle();
rectangle.BeginInit();
rectangle.Height = 100;
rectangle.Width = 100;
rectangle.Stroke = Brushes.Red;
rectangle.Fill = Brushes.Red;
rectangle.StrokeThickness = 1.0;
rectangle.Margin = new Thickness(0, 0, 0, 0);
rectangle.EndInit();
rectangle.Arrange(new Rect(new Size(100, 100)));
rectangle.UpdateLayout();
rtb.Render(rectangle);
var png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
using (Stream fs = File.Create("test.png"))
{
png.Save(fs);
}