Control not properly positioning programmatically - c#

So im trying to place an Ellipse (named Dot) on a random location inside a grid.
But it only spawns on 1/4th (lower right) of the grid instead of the complete grid.
Example: When i put the margin of the Dot to Dot.Margin = new Thickness(0, 0, 0, 0); the Dot will spawn in the center of the screen. When i change it to Dot.Margin = new Thickness(200, 0, 0, 0); it will have a very small offset to the right but not even close to 200 pixels.
Outcome after creating alot of circles without removing them:
http://i.imgur.com/3XCMYyC.png
The red rectangle is the spawn area.
C#
//Gives Dot a position
public void placeDot()
{
//Give Dot random position
// The farthest left the dot can be
double minLeft = 0;
// The farthest right the dot can be without it going off the screen
double maxLeft = spawnArea.ActualWidth - Dot.Width;
// The farthest up the dot can be
double minTop = 0;
// The farthest down the dot can be without it going off the screen
double maxTop = spawnArea.ActualHeight - Dot.Height;
double left = RandomBetween(minLeft, maxLeft);
double top = RandomBetween(minTop, maxTop);
Dot.Margin = new Thickness(left, top, 0, 0);
}
//createEllipse method, used for creating new Dots
public void createEllipse()
{
spawnArea.Children.Remove(Dot);
//Create new Dot
DotImg.ImageSource =
new BitmapImage(new Uri(#"Images/hitcircle.png", UriKind.Relative));
Dot = new Ellipse() { Width = hitcircleSettingPath, Height = hitcircleSettingPath, Fill = DotImg, };
//Activates placeDot() method to give the Dot a random location
placeDot();
//Add Dot to the game area
spawnArea.Children.Add(Dot);
}
XAML This is the complete XAML i think there might be something wrong with the XAML but below is a shorter snippet where it does work how i want it but without the other stuff.
<Window x:Name="Grid" x:Class="ReactieSnelheid_Game.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ReactieSnelheid_Game"
mc:Ignorable="d"
Title="Dot Program" Height="768" Width="1366" WindowStartupLocation="CenterScreen" Cursor="Pen" Icon="Images/icon.ico" ResizeMode="NoResize" WindowState="Maximized" WindowStyle="None" Background="Black" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Foreground="{x:Null}" KeyDown="Grid_KeyDown">
<Grid x:Name="backgroundImageGrid" Margin="0,0,0,0" MouseDown="LayoutRoot_MouseDown">
<Grid.Background>
<ImageBrush x:Name="backgroundBrush" ImageSource="Images/background.png" Opacity="0.25"/>
</Grid.Background>
<Grid x:Name="gameWrapper">
<Grid.Background>
<SolidColorBrush Color="Black" Opacity="0.25"/>
</Grid.Background>
<Label x:Name="reactionTime" Content="1000ms" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" FontSize="40" FontFamily="PMingLiU-ExtB" Foreground="White"/>
<Label x:Name="circleSize" Content="150x150" HorizontalAlignment="Left" Margin="10,73,0,0" VerticalAlignment="Top" FontSize="26.667" FontFamily="PMingLiU-ExtB" Foreground="White" Background="{x:Null}"/>
<Label x:Name="dotCount" Content="000000" HorizontalAlignment="Left" Margin="28,0,0,-1" Foreground="White" FontSize="80" RenderTransformOrigin="0.5,0.5" FontFamily="PMingLiU-ExtB" VerticalAlignment="Bottom" Background="{x:Null}">
<Label.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform AngleX="-11.056"/>
<RotateTransform/>
<TranslateTransform X="-8.305"/>
</TransformGroup>
</Label.RenderTransform>
</Label>
<Label x:Name="scoreCount" Content="9999999999999999" Margin="0,0,10,10" Foreground="White" FontSize="80" FontFamily="PMingLiU-ExtB" HorizontalAlignment="Right" Height="106" VerticalAlignment="Bottom"/>
<Rectangle x:Name="startTimerBtn" RenderTransformOrigin="0.39,-0.75" Margin="144,10,0,0" Width="128" Height="64" HorizontalAlignment="Left" VerticalAlignment="Top" MouseDown="startTimerBtn_MouseDown">
<Rectangle.Fill>
<ImageBrush ImageSource="Images/starttimer.png"/>
</Rectangle.Fill>
</Rectangle>
<Grid x:Name="spawnArea" Margin="0,115,0,121" Background="Red"/>
</Grid>
<Grid x:Name="pauseScreen">
<Grid.Background>
<SolidColorBrush Color="#FF81D650" Opacity="0.25"/>
</Grid.Background>
<Grid x:Name="pauseScreenBtns" Margin="389,153,389,152" HorizontalAlignment="Center" VerticalAlignment="Center">
<Rectangle x:Name="Startbtn" Height="332" Width="332" MouseDown="Startbtn_MouseDown" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="129,0,127,76">
<Rectangle.Fill>
<ImageBrush ImageSource="Images/Start.png"/>
</Rectangle.Fill>
</Rectangle>
<Rectangle x:Name="settingsBtn" MouseDown="settingsBtn_MouseDown" Margin="-5,189,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="129" Height="63">
<Rectangle.Fill>
<ImageBrush ImageSource="Images/settings.png"/>
</Rectangle.Fill>
</Rectangle>
<Rectangle x:Name="resetBtn" MouseDown="resetBtn_MouseDown" Margin="0,190,-6,0" Width="128" Height="62" HorizontalAlignment="Right" VerticalAlignment="Top">
<Rectangle.Fill>
<ImageBrush ImageSource="Images/reset.png"/>
</Rectangle.Fill>
</Rectangle>
<Rectangle x:Name="quitBtn" RenderTransformOrigin="0.39,-0.75" Margin="232,399,0,0" Width="129" Height="64" HorizontalAlignment="Left" VerticalAlignment="Top" MouseDown="quitBtn_MouseDown">
<Rectangle.Fill>
<ImageBrush ImageSource="Images/quit.png"/>
</Rectangle.Fill>
</Rectangle>
</Grid>
</Grid>
</Grid>
</Window>
Shorter XAML
<Window x:Class="TESTPROJECTEN.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TESTPROJECTEN"
mc:Ignorable="d"
Title="MainWindow" Height="768" Width="1366">
<Grid x:Name="gameWrapper">
<Grid x:Name="spawnArea"/>
</Grid>
</Window>

Ellipse has Alignment = Stretch by default. But you set a fixed Width and Height so it looks like ellipse is centered. Try set location relative to top left corner
Dot = new Ellipse() { Width = hitcircleSettingPath, Height = hitcircleSettingPath, Fill = DotImg, };
Dot.HorizontalAlignment = HorizontalAlignment.Left;
Dot.VerticalAlignment = VerticalAlignment.Top;

it will have a very small offset to the right but not even close to
200 pixels.
First of all, as far as I remember, WPF doesn't use those numbers as pixels, but as some internal values. I can't remember the name of those units, but bottom line, they are not pixels.
Now for your actual problem:
Wpf grid places all his child controls by default in the center, so when you are putting the ellipse inside the grid and set a margin 200, it sets the margin from the center.
With that in mind, you can change your random algorithm to make the bubbles appear all over the grid:
//Gives Dot a position
public void placeDot()
{
//Give Dot random position
double halfSide = (spawnArea.ActualWidth - Dot.Width) / 2;
// The farthest left the dot can be
double minLeft = -(halfSide - (Dot.ActualWidth / 2));
// The farthest right the dot can be without it going off the screen
double maxLeft = halfSide - (Dot.ActualWidth / 2);
// The farthest up the dot can be
double minTop = -(halfSide - (Dot.ActualHeight / 2));
// The farthest down the dot can be without it going off the screen
double maxTop = halfSide - (Dot.ActualHeight / 2);
double left = RandomBetween(minLeft, maxLeft);
double top = RandomBetween(minTop, maxTop);
Dot.Margin = new Thickness(left, top, 0, 0);
}
I hope I didn't miss anything. I didn't run this code, so it might need adjustments, but this is the main line to follow.
Happy Coding! :)

Related

WPF RenderTargetBitmap returns a black image

I have to "export" a UserControl as an image, I've tried to use RenderTargetBitmap, but this outputs a black image. I tried online solution, but I seem to be missing something.
Here is my code:
UserControl usage :
<uc:ImageStatusBar x:Name="OverlayPanel" Grid.Column="2" Grid.Row="1" HorizontalAlignment="Stretch"/>
UserControl code :
<UserControl x:Class="ImageViewer.Controls.ImageStatusBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ImageViewer.Controls"
xmlns:uc="clr-namespace:ImageViewer.Controls"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid x:Name="StatusbarGrid" Grid.Column="2" Grid.Row="1" HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="8*"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<StatusBar x:Name="LeftSideStaticStatusBar" Grid.Column="0">
<StatusBar.Background>
<SolidColorBrush Color="White" Opacity="0.5"/>
</StatusBar.Background>
<StatusBarItem x:Name="Logo" Height="42" Width="42" HorizontalAlignment="Right" Padding="6,0,0,0">
<Image x:Name="LogoImage"></Image>
</StatusBarItem>
</StatusBar>
<StatusBar x:Name="StatusBar" ItemsSource="{Binding}" Grid.Column="1" Padding="6,0,0,0">
<StatusBar.Background>
<SolidColorBrush Color="White" Opacity="0.5"/>
</StatusBar.Background>
<StatusBar.ItemTemplate>
<DataTemplate>
<Border BorderThickness="4 0 4 0">
<uc:StatusBarItem HorizontalAlignment="Left"/>
</Border>
</DataTemplate>
</StatusBar.ItemTemplate>
</StatusBar>
<StatusBar x:Name="RightSideStaticStatusBar" Grid.Column="2">
<StatusBar.Background>
<SolidColorBrush Color="White" Opacity="0.5"></SolidColorBrush>
</StatusBar.Background>
<StatusBarItem x:Name="IntensityBarItem" HorizontalAlignment="Right" HorizontalContentAlignment="Stretch" Width="128">
<uc:IntensityBar x:Name="IntensityBarControl" ViewModel="{Binding}"/>
</StatusBarItem>
<StatusBarItem x:Name="ScaleBarItem" HorizontalAlignment="Right" HorizontalContentAlignment="Stretch" Width="100">
<uc:ScaleBar x:Name="ScaleBarControl" ViewModel="{Binding}"></uc:ScaleBar>
</StatusBarItem>
</StatusBar>
</Grid>
</UserControl>
And the code to Generate the image. For now it's a double click on the the actual UC as I yet in the "design" part of the functionality.
private void OverlayPanel_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
RenderTargetBitmap bitmap =
new RenderTargetBitmap((int)OverlayPanel.ActualWidth,
(int)OverlayPanel.ActualHeight,
96, 96, PixelFormats.Pbgra32);
bitmap.Render(OverlayPanel);
int width = bitmap.PixelWidth;
int height = bitmap.PixelHeight;
int componentsPerPixel = 4;
int totalPixels = width * height;
int totalBytes = totalPixels * componentsPerPixel;
byte[] rgbValues = new byte[totalBytes];
var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight];
bitmap.CopyPixels(rgbValues, bitmap.PixelWidth * bitmap.Format.BitsPerPixel / 8, 0);
using (FileStream stream = File.Create(#"D:\image3.png"))
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 90;
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(stream);
// If you want to export the xamDataChart to a PNG
// instead of JPEG, use this code block:
// PngBitmapEncoder encoder = new PngBitmapEncoder();
// encoder.Frames.Add(BitmapFrame.Create(bitmap));
// encoder.Save(stream);
}
}
What I am missing here? Is this the proper solution, should I try and focus on creating the image from "scratch" using the text in the component?
Two more things to mention:
uc:IntensityBar <-- it's an other image
uc:ScaleBar <-- is a grid with some lines.

Changed MatrixTransform result control out of bounds

I'm writing an image control with zoom, and wrap into a usercontrol.
<UserControl x:Class="WpfApp20.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp20"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid Background="Green">
<Grid x:Name="gridMain" MouseWheel="gridMain_MouseWheel">
<Viewbox Stretch="Uniform">
<Grid x:Name="SIGrid">
<Grid.RenderTransform >
<TransformGroup >
<MatrixTransform x:Name="MatrixTransform" />
</TransformGroup>
</Grid.RenderTransform>
<Image x:Name="PART_MainImage" Source="/Grid.png" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" SnapsToDevicePixels="True" Stretch="Uniform" StretchDirection="Both" Visibility="Visible">
</Image>
</Grid>
</Viewbox>
</Grid>
</Grid>
</UserControl>
private void gridMain_MouseWheel(object sender, MouseWheelEventArgs e)
{
try
{
if (MatrixTransform == null)
return;
var pos = e.GetPosition(PART_MainImage);
var scale = e.Delta > 0 ? 1.1 : 1 / 1.1;
var matrix = MatrixTransform.Matrix;
if (matrix.M11 <= 0.1 && e.Delta < 0)
return;
MatrixTransform.Matrix = new Matrix(scale, 0, 0, scale, pos.X - (scale * pos.X), pos.Y - (scale * pos.Y)) * matrix;
}
catch (Exception ex)
{
}
}
Then in MainWindow, I just put it into a grid.
<Grid Background="Red"/>
<Grid Grid.Row="1">
<local:UserControl1/>
</Grid>
So when I zoom in, the image goes out of the usercontrol bounds, it should always in the green area.
How to fix?
I made a sample here.
Finally, ClipToBounds saved me.
<Grid Background="Green" ClipToBounds="True">

How do i apply a TranslateTransform on an existing 'Children'

I'm rewriting this question to try and make it clearer to people what ive done, trying to do etc.
I am involved in a project where im trying to make some visual displays. One display is a dial, and i pretty much got entire code from this link.
https://github.com/mesta1/WPF-Circular-Gauge/blob/master/CircularGauge/CircularGaugeDemoWPF/CircularGaugeDemoWPF.csproj
I am now trying to do a verticle guage, bit like below.
now ive modified the dial code so background scale etc all works.
The issue im having is the moving indicator.
The dial code defines the dial in the xaml like the following.
<Path x:Name="Pointer" Stroke="#FFE91C1C" StrokeThickness="2"
Width="{TemplateBinding PointerLength}"
Height="{TemplateBinding PointerThickness}"
HorizontalAlignment="Center"
Data="M1,1 L1,10 L156,6 z" Stretch="Fill"
RenderTransformOrigin="0,0.5"
RenderTransform="{Binding RelativeSource=
{RelativeSource TemplatedParent}, Path=PointerLength,
Converter={StaticResource pointerCenterConverter}}">
and in the .cs file controls its position like the following.
TransformGroup tg = pointer.RenderTransform as TransformGroup;
RotateTransform rt = tg.Children[0] as RotateTransform;
rt.Angle = angleValue;
now as im only moving the indicator vertically up and down, i believe that i need a TranslateTransform. With the help of Sheridan. Ive changed my xaml to the following.
<Path x:Name="Pointer" Stroke="#FFE91C1C" StrokeThickness="2"
VerticalAlignment="Bottom"
Data="M 0,0 L 16,-5 L16,5 L0,0 z">
<Path.RenderTransform>
<TransformGroup>
<TranslateTransform/>
</TransformGroup>
</Path.RenderTransform>
now im struggling with what my .cs needs to be to edit this. Currently im playing with
TransformGroup tg = pointer.RenderTransform as TransformGroup;
TranslateTransform rt = tg.Children[0] as TranslateTransform;
rt.Y = -10;
this however throws error "Cannot set a property on object 'System.Windows.Media.TranslateTransform' because it is in a read-only state."
i have been advised again by Sheridan to try assigning a new object adn replacing the old. But what i seems to try either throws errors or has no effect.
In order to transform a UIElement, you first need to apply a transformation element on it:
<Path ... >
<Path.RenderTransform>
<TranslateTransform />
</Path.RenderTransform>
</Path>
If you are using a TranslateTransform as your RenderTransform property value, then you cannot cast it to a RotateTransform. You can find out more from the UIElement.RenderTransform Property page on MSDN.
TransformGroup tg = pointer.RenderTransform as TransformGroup;
// tg == null
Likewise, if you try to cast this property value to a TransformGroup without setting one, then you will get a null value:
<Path ... >
<Path.RenderTransform>
<TransformGroup>
<ScaleTransform />
<RotateTransform />
</TransformGroup>
</Path.RenderTransform>
</Path>
You can find out more from the TransformGroup Class page on MSDN.
...
TransformGroup tg = pointer.RenderTransform as TransformGroup;
// tg is a TransformGroup
Please find the simple working code of dynamic Transform. I hope It will help you
WPF
<Window x:Class="WPFAnimationSample2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Ellipse x:Name="animateEllipse" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="61" Margin="99,78,0,0" Stroke="Black" VerticalAlignment="Top" Width="81" RenderTransformOrigin="0.5,0.5" >
<Ellipse.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform X="1" Y="1"/>
</TransformGroup>
</Ellipse.RenderTransform>
</Ellipse>
<Button Content="Button" HorizontalAlignment="Left" Margin="180,256,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
C#
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void checkAnimation()
{
TransformGroup tg = animateEllipse.RenderTransform as TransformGroup;
TranslateTransform rt = tg.Children[3] as TranslateTransform;
rt.X = rt.X+100;
rt.Y = 100;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
checkAnimation();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
checkAnimation();
}
}

Fill Ellipse based on percentage

I have created Ellipse in XAML.
Here is the code :
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Ellipse Width="400" Stroke="DodgerBlue" Height="400" StrokeThickness="75" Fill="Transparent">
</Ellipse>
</Grid>
Say the Ellipse is 100% if its 20% the blue color should fill only till that and also display the percentage text in the center (empty area) of ellipse.
EDIT
I have add text to display in center.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Ellipse Width="400" Stroke="DodgerBlue" Height="400" StrokeThickness="75" Fill="Transparent">
</Ellipse>
<TextBlock VerticalAlignment="Center"
HorizontalAlignment="Center"
Text="20"
FontSize="125"/>
</Grid>
EDIT 2
Here is what how it looks like i am trying to acheive:
here the orange color with the 20% fill.
You can use an arc control preset in the assembly Microsoft.Expression.Drawing
It has properties like StartAngle and EndAngle which could be well manipulated accordingly.
<es:Arc x:Name="arc" ArcThickness="3" ArcThicknessUnit="Pixel" EndAngle="360" Fill="Black" Height="270" Canvas.Left="101.94" Stroke="Black" StartAngle="0" UseLayoutRounding="False" Width="269.941" Canvas.Top="12" />
Now what you could do using this control is : Just take two similar arcs One superimposing the other,
color the below one(1st arc) with Blue and give start and end angle properties to the red color arc(2nd arc) which would make your layout look like the way it is mentioned in design two.
Raw Usage:
<Canvas x:Name="canvas1" Margin="0,10,0,0" Height="300" Width="480" HorizontalAlignment="Center">
<es:Arc x:Name="arc" ArcThickness="3" ArcThicknessUnit="Pixel" Fill="Black" Height="100" Canvas.Left="0" Stroke="Blue" UseLayoutRounding="False" Width="100" Canvas.Top="0"/>
</Canvas>
<es:Arc x:Name="arc" ArcThickness="3" EndAngle="120" StartAngle="0" ArcThicknessUnit="Pixel" Fill="Blue" Height="100" Canvas.Left="0" Stroke="Blue" UseLayoutRounding="False" Width="100" Canvas.Top="0"/>
</Canvas>
Check this link as well
User control version would consist of two parts: XAML + code-behind.
XAML part:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Project.CustomControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
mc:Ignorable="d"
d:DesignHeight="40"
d:DesignWidth="40">
<Grid Width="40" Height="40">
<Ellipse StrokeThickness="3" Stroke="#FF89CE25"/>
<Path Stroke="Red" StrokeThickness="2" x:Name="arcPath">
<Path.Data>
<PathGeometry>
<PathFigure StartPoint="20,1">
<ArcSegment x:Name="myArc" SweepDirection="Clockwise" IsLargeArc="True" Point="20,1"/>
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
</Grid>
Code-behind file (short version, no fluff):
public sealed partial class MyCustomControl : UserControl
{
public double ProgressValue
{
get { return (double)GetValue(ProgressValueProperty); }
set { SetValue(ProgressValueProperty, value); }
}
// Using a DependencyProperty as the backing store for ProgressValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ProgressValueProperty =
DependencyProperty.Register("ProgressValue", typeof(double), typeof(MyCustomControl), new PropertyMetadata(0.0, OnProgressValueChanged));
private static void OnProgressValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//throw new NotImplementedException();
MyCustomControl circularProgressBar = d as MyCustomControl;
if (circularProgressBar != null)
{
double r = 19;
double x0 = 20;
double y0 = 20;
circularProgressBar.myArc.Size = new Size(19, 19);
double angle = 90 - (double)e.NewValue / 100 * 360;
double radAngle = angle * (PI / 180);
double x = x0 + r * Cos(radAngle);
double y = y0 - r * Sin(radAngle);
if (circularProgressBar.myArc != null)
{
circularProgressBar.myArc.IsLargeArc = ((double)e.NewValue >= 50);
circularProgressBar.myArc.Point = new Point(x, y);
}
}
}
public MyCustomControl()
{
this.InitializeComponent();
}
}
Now, you can throw your CustomControl into any place in your XAML and bind the ProgressValue property to the respective data source. The arc would redraw itself and will fill the Ellipse shape proportionally to the value (a value from 0-100).

Overlay bitmaps (writeablebitmap etc.) in windows store app

I have 2 bitmaps (foreground and background) which I need to overlay on top of each other to form a new bitmap and use it as the ImageBrush for a button.
The code would look something like this (Windows 8.1 store app):
WriteableBitmap foregroundBitmap = GetForegroundBitmap();
WriteableBitmap backgroundBitmap = GetBackgroundBitmap();
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = Overlay(foregroundBitmap, backgroundBitmap);
Button button = new Button();
button.Background = imageBrush;
How can I implement the Overlay(...) method above?
I tried:
backgroundBitmap.Blit(
new Rect(0, 0, backgroundBitmap.PixelWidth, backgroundBitmap.PixelHeight),
foregroundBitmap,
new Rect(0, 0, foregroundBitmap.PixelWidth, foregroundBitmap.PixelHeight),
WriteableBitmapExtensions.BlendMode.None);
but it didn't work (with BlendedMode None or Additive).
Thanks.
Try this
<Window.Resources>
<BitmapImage x:Key="image1" UriSource="DefaultImage.png"></BitmapImage>
<BitmapImage x:Key="image2" UriSource="ImageRoation.png"></BitmapImage>
</Window.Resources>
<Button Height="200" Width="200">
<Grid Height="200" Width="200">
<Grid.Background>
<ImageBrush ImageSource="{StaticResource image1}" Stretch="Fill" ></ImageBrush>
</Grid.Background>
<Grid Margin="5" Width="50" Height="50">
<Grid.Background>
<ImageBrush ImageSource="{StaticResource image2}" Stretch="Fill"></ImageBrush>
</Grid.Background>
</Grid>
</Grid>
</Button>

Categories