Image control and Image resizing when Stretch is set to Uniform - c#

I have this peculiar problem. I am having a user control . I am making an app for Windows 8.1 where I would choose an image from my Picture gallery. The image would open in my app with Stretch is Uniform and Horizontal And vertical alignment to center.
My user control will appear where I tap on the image. Now the problem is , when the image Stretch was none , I was able to magnify the correct region (around my click) , but now when I make it Stretch to Uniform and Set the horizontal and vertical Alignment to Center , I am getting other pixel information in my user control.
I want to know how to fix it.Any how , the images can be of 2*Full HD also or they can be HD or even less.
Secondly , I want to know the boundaries of the image . With boundaries I want to say that , my user control shouldnt go above the boundaries of the image .
How to implement that. If my code is needed , I would paste it , If required.
Have this video for reference . This is what I have to develop ! I have the user control ready and I am getting exact pixels for Stretch=NONE , and no Horizontal And Vertical Alignment set.
This is my code for my app

I believe the issue is with how you use the control, rather than the image. If you avoid doing the bitmap cropping and replacing, it would speed up dramatically and likely work for all stretch types.
I've modified the source to show this - removing the Cropping completely. If you need cropping for other reasons, you should consider using the unsafe keyword (and property setting to allow) in order to dramatically speed up its use.
Also, to avoid the lagging/jumping upward, I added IsHitTestVisible="False" so that your delta wouldn't be interrupted by hovering over your image.
I see you have the 45-degree code already - since it wasn't in your source, I only added an example of 90 degree rotation when you get to the sides - so you can see how to set a RenderTransformOrigin point.
MainPage.xaml:
<Page x:Name="page1"
x:Class="controlMagnifier.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:controlMagnifier"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid x:Name="ParentGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" PointerReleased="ParentGrid_OnPointerReleased" >
<Canvas x:Name="InkPresenter" Height="auto" Width="auto">
<Image Stretch="Uniform" x:Name="image2" >
<Image.Source >
<BitmapImage UriSource="/Assets/wallpaper.jpg" />
</Image.Source>
</Image>
</Canvas>
<local:MagnifierUsercontrol x:Name="MagnifyTip" Visibility="Collapsed" ManipulationMode="All"
IsHitTestVisible="False" Height="227" Width="171"
VerticalContentAlignment="Bottom" HorizontalContentAlignment="Center">
</local:MagnifierUsercontrol>
</Grid>
</Page>
MainPage.xaml.cs:
using System;
using Windows.Foundation;
using Windows.Storage;
using Windows.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
namespace controlMagnifier
{
public sealed partial class MainPage : Page
{
public const int XAxis = 200;
public const int YAxis = 435;
private readonly RotateTransform myRotateTransform = new RotateTransform {CenterX = 0.5, CenterY = 1};
private readonly ScaleTransform myScaleTransform = new ScaleTransform {ScaleX = 1, ScaleY = 1};
private readonly TransformGroup myTransformGroup = new TransformGroup();
private readonly TranslateTransform myTranslateTransform = new TranslateTransform();
public WriteableBitmap CurrentBitmapObj, CurrentCroppedImage = null;
public Point currentContactPt, GridPoint;
public Thickness margin;
public PointerPoint pt;
public double xValue, yValue;
public MainPage()
{
InitializeComponent();
ParentGrid.Holding += Grid_Holding;
image2.PointerMoved += InkCanvas_PointerMoved;
image2.PointerReleased += ParentGrid_OnPointerReleased;
margin = MagnifyTip.Margin;
image2.CacheMode = new BitmapCache();
myTransformGroup.Children.Add(myScaleTransform);
myTransformGroup.Children.Add(myRotateTransform);
myTransformGroup.Children.Add(myTranslateTransform);
MagnifyTip.RenderTransformOrigin = new Point(0.5, 1);
MagnifyTip.RenderTransform = myTransformGroup;
}
private void Grid_Holding(object sender, HoldingRoutedEventArgs e)
{
try
{
GridPoint = e.GetPosition(image2);
myTranslateTransform.X = xValue - XAxis;
myTranslateTransform.Y = yValue - YAxis;
MagnifyTip.RenderTransform = myTransformGroup;
MagnifyTip.Visibility = Visibility.Visible;
}
catch (Exception)
{
throw;
}
}
private void InkCanvas_PointerMoved(object sender, PointerRoutedEventArgs e)
{
try
{
pt = e.GetCurrentPoint(image2);
currentContactPt = pt.Position;
xValue = currentContactPt.X;
yValue = currentContactPt.Y;
if (xValue > 300)
{
myRotateTransform.Angle = -90;
}
else if (xValue < 100)
{
myRotateTransform.Angle = 90;
}
else
{
myRotateTransform.Angle = 0;
}
MagnifyTip.RenderTransform = myRotateTransform;
myTranslateTransform.X = xValue - XAxis;
myTranslateTransform.Y = yValue - YAxis;
MagnifyTip.RenderTransform = myTransformGroup;
}
catch (Exception)
{
throw;
}
finally
{
e.Handled = true;
}
}
private async void StoreCrrentImage()
{
try
{
var storageFile =
await
StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/wallpaper.jpg",
UriKind.RelativeOrAbsolute));
using (
var fileStream =
await storageFile.OpenAsync(FileAccessMode.Read))
{
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
var writeableBitmap =
new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
fileStream.Seek(0);
await writeableBitmap.SetSourceAsync(fileStream);
CurrentBitmapObj = writeableBitmap;
writeableBitmap.Invalidate();
}
}
catch (Exception)
{
// Graphics g=new Graphics();
throw;
}
finally
{
}
}
private void ParentGrid_OnPointerReleased(object sender, PointerRoutedEventArgs e)
{
MagnifyTip.Visibility = Visibility.Collapsed;
}
}
}
MagnifierUsercontrol.xaml:
<UserControl
x:Class="controlMagnifier.MagnifierUsercontrol"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:controlMagnifier"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Height="227" Width="171">
<Canvas x:Name="controlCanvas" x:FieldModifier="public" Height="Auto" Width="Auto" >
<Grid Height="227" Width="171" HorizontalAlignment="Center" Canvas.Left="0" Canvas.Top="0">
<Border x:FieldModifier="public" x:Name="imgBorder" Width="150" CornerRadius="50,50,50,50" Margin="13,25,13,97">
<Border.Background>
<ImageBrush x:FieldModifier="public" x:Name="image1" />
</Border.Background>
</Border>
<TextBlock x:Name="txtreading" Height="30" Width="80" Margin="0,-145,0,0" FontWeight="Bold" Foreground="Red" FontSize="20" Text="ABC" TextAlignment="Center" />
<!--<Image Height="120" Width="150" Margin="0,-50,0,0" Source="Assets/SmallLogo.scale-100.png" ></Image>-->
<Path x:Name="MagnifyTip" Data="M25.533,0C15.457,0,7.262,8.199,7.262,18.271c0,9.461,13.676,19.698,17.63,32.338 c0.085,0.273,0.34,0.459,0.626,0.457c0.287-0.004,0.538-0.192,0.619-0.467c3.836-12.951,17.666-22.856,17.667-32.33 C43.803,8.199,35.607,0,25.533,0z M25.533,32.131c-7.9,0-14.328-6.429-14.328-14.328c0-7.9,6.428-14.328,14.328-14.328 c7.898,0,14.327,6.428,14.327,14.328C39.86,25.702,33.431,32.131,25.533,32.131z" Fill="#FFF4F4F5" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" Height="227" Width="171" />
</Grid>
</Canvas>
</UserControl>
Let me know if this helps or if there is further toward your specific question.

Related

WPF Changing fill colour of ellipse

So I'm trying to make 8 circles which all have different fill colours and all have different blinking speeds. So far I have been able to make them blink at different speeds, but I'm having trouble with making them all have different colours. My code so far:
private void Appear(Ellipse element, double duration, Brush colour)
{
element.Fill = colour;
DoubleAnimation db = new DoubleAnimation();
db.From = 0.0;
db.To = 1.0;
db.Duration = new Duration(TimeSpan.FromSeconds(duration));
db.RepeatBehavior = RepeatBehavior.Forever;
element.BeginAnimation(Ellipse.OpacityProperty, db);
}
private Brush SetEllipseColour(Ellipse element)
{
Random rnd = new Random();
int red = rnd.Next(0, 255);
int green = rnd.Next(0, 255);
int blue = rnd.Next(0, 255);
Brush fillColour = new SolidColorBrush(Color.FromRgb((byte)red, (byte)green, (byte)blue));
return fillColour;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
List<Ellipse> elements = new List<Ellipse>();
elements.Add(Circle1);
elements.Add(Circle2);
elements.Add(Circle3);
elements.Add(Circle4);
elements.Add(Circle5);
elements.Add(Circle6);
elements.Add(Circle7);
elements.Add(Circle8);
Random rnd = new Random();
foreach (Ellipse element in elements)
{
int r = rnd.Next(1, 10);
double duration = (Double)r / 10;
Appear(element, duration, SetEllipseColour(element));
}
}
And my WPF:
<Canvas Margin="10">
<Ellipse
x:Name="Circle1"
Fill="Black"
Height="100"
Width="100"/>
<Ellipse
x:Name="Circle2"
Fill="Black"
Height="100"
Width="100"
Margin="120,0,0,0"/>
<Ellipse
x:Name="Circle3"
Fill="Black"
Height="100"
Width="100"
Margin="240,0,0,0"/>
<Ellipse
x:Name="Circle4"
Fill="Black"
Height="100"
Width="100"
Margin="360,0,0,0"/>
<Ellipse
x:Name="Circle5"
Fill="Black"
Height="100"
Width="100"
Margin="0,120,0,0"/>
<Ellipse
x:Name="Circle6"
Fill="Black"
Height="100"
Width="100"
Margin="120,120,0,0"/>
<Ellipse
x:Name="Circle7"
Fill="Black"
Height="100"
Width="100"
Margin="240,120,0,0"/>
<Ellipse
x:Name="Circle8"
Fill="Black"
Height="100"
Width="100"
Margin="360,120,0,0"/>
</Canvas>
<Button x:Name="button1" Content="Start" Width="80" Height="20" Margin="0,200,0,0" Click="button1_Click"/>
Note: I know I can compress / change my code to make it neater or better, but for now I just want to get the colours working.
So currently the code I have changes the fill colour of all Ellipse elements, but I want to change it to just affect each Circle. How would I go about doing this?
Edit:
For those who are confused what Im trying to ask, I do not know how to individually change the fill colour of every Circle.
Set the instance of the Random class at the class level, check the below example, by clicking on the the Button that says Blink Em! the animation is triggered.
The XAML
<Window x:Class="Blink.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:Blink"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" WindowState="Maximized">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Button x:Name="BlinkEm" Content="Blink Em!" Height="30" Click="BlinkEm_Click"/>
<StackPanel x:Name="Container" Orientation="Horizontal" Loaded="Container_Loaded" Grid.Row="1"/>
</Grid>
</Window>
The code-behind
namespace Blink
{
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public Random random = new Random();
public MainWindow()
{
InitializeComponent();
}
public List<Ellipse> CreateCircles(int count)
{
List<Ellipse> circles = new List<Ellipse>();
for (int i = 0; i < count; i++)
{
var circle = new Ellipse
{
Height = 100,
Width = 100,
Margin = new Thickness(10),
Fill = Brushes.SkyBlue
};
circles.Add(circle);
}
return circles;
}
public void AddCircles()
{
var circles = this.CreateCircles(8);
foreach (var circle in circles)
{
Container.Children.Add(circle);
}
}
private void Container_Loaded(object sender, RoutedEventArgs e)
{
AddCircles();
}
private void BlinkEm_Click(object sender, RoutedEventArgs e)
{
foreach (Ellipse circle in Container.Children)
{
circle.Fill = GetRandomColor();
circle.BeginAnimation(Ellipse.OpacityProperty, GetBlinkAnimation());
}
}
public Brush GetRandomColor()
{
var red = Convert.ToByte(random.Next(0, 255));
var green = Convert.ToByte(random.Next(0, 255));
var blue = Convert.ToByte(random.Next(0, 255));
return new SolidColorBrush(Color.FromRgb(red, green, blue));
}
public DoubleAnimation GetBlinkAnimation()
{
var duration = random.NextDouble();
var animation = new DoubleAnimation
{
From = 0.0,
To = 1.0,
Duration = new Duration(TimeSpan.FromSeconds(duration)),
RepeatBehavior = RepeatBehavior.Forever
};
return animation;
}
}
}
I think your mistake here is that the Random object is being recreated every time. Try putting that into a field and initializing it once, or by sending it as a parameter to your SetEllipseColor method.
Due to random number generators not actually being random, they derive their "initial" random values from a seed value, often the current time. This means if you create a bunch of new Random instances in a very short time, they are likely to end up with the same seed and thus the same value.
(In more general terms, "Appear" and "SetEllipseColor" aren't very good method names. The former is vague and the latter doesn't actually describe what that method is doing.)

Scale, translate and crop an image in windows phone 8.1 silverlight

I need the functionality of an image scale, translate and cropping just like what a photo chooser task do in windows phone 8.1. I can not use photo chooser task because I will not select the photo from media photo library or capture the image. For my purpose the image will be selected from a server saved picture list. I have written some code for this but it's not working as I desire. I am working on it for 4 weeks but hardly find the perfect solution. Here is my code.
This is the xaml code
<phone:PhoneApplicationPage
x:Class="TransformationLearning.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="Transformation" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid Grid.Row="1" Background="Yellow">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Name="grid"
Grid.Row="0"
Height="400"
Width="400"
>
<Image x:Name="myImage" Source="/Assets/Lion.jpg"
Stretch="UniformToFill"
ManipulationCompleted="CompleteManipulation"
ManipulationDelta="DeltaManipulation"
Loaded="ImageLoaded"
Grid.Row="1"
>
<Image.RenderTransform>
<CompositeTransform x:Name="myComposite"
/>
</Image.RenderTransform>
</Image>
<Rectangle Width="200"
Height="200"
Name="myRectangle"
Margin="100 100"
Stroke="White"
StrokeThickness="3" Grid.Row="1">
</Rectangle>
</Grid>
<Image Name="myCropPicture" Grid.Row="1"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
and this is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using TransformationLearning.Resources;
using Microsoft.Xna.Framework;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
using Lumia.Imaging;
using Lumia.Imaging.Transforms;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.Storage;
using System.Windows.Controls.Primitives;
using System.Runtime.InteropServices.WindowsRuntime;
namespace TransformationLearning
{
public partial class MainPage : PhoneApplicationPage
{
WriteableBitmap WB_CapturedImage;//for original image
WriteableBitmap WB_CroppedImage;//for cropped image
double width, height;
WriteableBitmap wb;
CompositeTransform transform;
GeneralTransform gt, gt1;
System.Windows.Point absolutePosition, absolutePosition1;
public MainPage()
{
InitializeComponent();
transform = new CompositeTransform();
}
private void ImageLoaded(object sender, RoutedEventArgs e)
{
wb = new WriteableBitmap(myImage, null);
myComposite.CenterX = 150;
myComposite.CenterY = 150;
}
private double BoundaryCheck(double value)
{
if (value < 1.0)
return 1.0;
else if (value > 2.0)
return 2.0;
else
return value;
}
private void DeltaManipulation(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
{
transform = myComposite;
if (e.DeltaManipulation.Scale.X == 0.0 || e.DeltaManipulation.Scale.Y == 0.0)
{
myComposite.ScaleX *= 1.0;
myComposite.ScaleY *= 1.0;
}
else if (e.DeltaManipulation.Scale.X > 0.0)
{
double value = BoundaryCheck(myComposite.ScaleX*e.DeltaManipulation.Scale.X);
myComposite.ScaleX = myComposite.ScaleY = value;
gt = myImage.TransformToVisual(grid);
absolutePosition = gt.Transform(new System.Windows.Point(0, 0));
gt1 = myRectangle.TransformToVisual(grid);
absolutePosition1 = gt1.Transform(new System.Windows.Point(0, 0));
if ((absolutePosition1.X <= absolutePosition.X)
|| (absolutePosition1.Y <= absolutePosition.Y)
|| (absolutePosition1.X + myRectangle.Width >= absolutePosition.X + wb.PixelWidth)
|| (absolutePosition1.Y + myRectangle.Height >= absolutePosition.Y + wb.PixelHeight))
{
myComposite = transform;
}
}
gt = myImage.TransformToVisual(grid);
absolutePosition = gt.Transform(new System.Windows.Point(0, 0));
gt1 = myRectangle.TransformToVisual(grid);
absolutePosition1 = gt1.Transform(new System.Windows.Point(0, 0));
if (e.DeltaManipulation.Translation.Y > 0.0 && (absolutePosition1.Y >= (absolutePosition.Y + e.DeltaManipulation.Translation.Y)))
{
myComposite.TranslateY += (e.DeltaManipulation.Translation.Y-2);
}
if (e.DeltaManipulation.Translation.X > 0.0 && (absolutePosition1.X >= (absolutePosition.X + e.DeltaManipulation.Translation.X)))
{
myComposite.TranslateX += (e.DeltaManipulation.Translation.X - 2);
}
if (e.DeltaManipulation.Translation.Y < 0.0 && ((absolutePosition1.Y + myRectangle.Height) <= (absolutePosition.Y + e.DeltaManipulation.Translation.Y + wb.PixelHeight)))
{
myComposite.TranslateY += (e.DeltaManipulation.Translation.Y + 2);
}
if (e.DeltaManipulation.Translation.X < 0.0 && ((absolutePosition1.X + myRectangle.Width) <= (absolutePosition.X + e.DeltaManipulation.Translation.X + wb.PixelWidth)))
{
myComposite.TranslateX += (e.DeltaManipulation.Translation.X + 2);
}
wb = new WriteableBitmap(myImage, myComposite);
gt = myImage.TransformToVisual(grid);
absolutePosition = gt.Transform(new System.Windows.Point(0, 0));
}
private void CompleteManipulation(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
{
App.RootFrame.RenderTransform = new CompositeTransform();
grid.UpdateLayout();
CropImage();
App.RootFrame.RenderTransform = new CompositeTransform();
grid.UpdateLayout();
}
private async void CropImage()
{
var ms = new MemoryStream();
wb.SaveJpeg(ms, wb.PixelWidth, wb.PixelHeight, 0, 100);
ms.Position = 0;
gt1 = myRectangle.TransformToVisual(myImage);
absolutePosition1 = gt1.Transform(new System.Windows.Point(0, 0));
using (var source = new StreamImageSource(ms))
{
using (var filterEffect = new FilterEffect(source))
{
var filter = new CropFilter(new Windows.Foundation.Rect(absolutePosition1.X, absolutePosition1.Y, myRectangle.Width, myRectangle.Height));
filterEffect.Filters = new IFilter[] { filter };
var target = new WriteableBitmap((int)(myRectangle.Width), (int)(myRectangle.Height));
using (var renderer = new WriteableBitmapRenderer(filterEffect, target))
{
try
{
await renderer.RenderAsync();
}
catch (Exception t)
{
System.Diagnostics.Debug.WriteLine(t.InnerException);
System.Diagnostics.Debug.WriteLine(t.Message);
}
}
myCropPicture.Source = target;
}
}
}
}
}
Here I have used Lumia Imaging SDK crop filter for cropping the image. "myImage" is the source image and "myCropPicture" is used for showing the cropped image. For transformation I have used composite transform. When I scale the source image this code can not crop that image accordingly.I need the help badly.
did you check this post. it might come in handy
Image crop control for Silverlight or Windows Phone

Save didnt work the drawing WinRT

The application is running all good but when i'll go to save is like the margin move the picture and the drawing i do move too. What i'm doing wrong or what i need to do to fix that. I think is a geometry problem.
Xaml Code:
<Page
x:Class="DrawingWithMe.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DrawingWithMe"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Viewbox>
<Grid x:Name="Grid1" Height="768" Width="1366">
<Canvas x:Name="funnyCanvas" Background="White" Margin="162,10,254,42">
<Rectangle x:Name="Rectangle1" Fill="#FFF4F4F5" Stroke="Black"></Rectangle>
<Image x:Name="image" Source="Assets/Test.gif" Stretch="UniformToFill"/>
</Canvas>
</Grid>
</Viewbox>
<Page.BottomAppBar>
<AppBar x:Name="AppBar" Padding="10,0,10,0">
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<Button Name="Save" Content="Save" VerticalAlignment="Top" Click="Save_Click_1" Grid.Column="1"></Button>
<Button Name="Erase" Content="Erase All" VerticalAlignment="Top" Click="Erase_Click_1" Grid.Column="2"></Button>
<Button x:Name="Copytoclipboard" Content="Copy To ClipBoard" VerticalAlignment="Top" Click="Copytoclipboard_Click_1"></Button>
<Button x:Name="Pastefrom" Content="Paste From ClipBoard" VerticalAlignment="Top" Click="Pastefrom_Click_1"></Button>
<Button x:Name="Recognizeword" Content="Recognize" VerticalAlignment="Top" Click="Recognizeword_Click_1"></Button>
</StackPanel>
</Grid>
</AppBar>
</Page.BottomAppBar>
</Page>
C# Code:
public async void TestingBlit()
{
var backgroundBmp = await BitmapFactory.New(1, 1).FromContent(new Uri(BaseUri, #"///Assets/Test.gif"));
//Image foreground
WriteableBitmap foregroundBmp;
using (InMemoryRandomAccessStream a = new InMemoryRandomAccessStream())
{
await _inkManager.SaveAsync(a);
a.Seek(0);
foregroundBmp = await new WriteableBitmap(1,1).FromStream(a);
}
// Combined
backgroundBmp.Blit(new Rect(0, 0, foregroundBmp.PixelWidth, foregroundBmp.PixelHeight), foregroundBmp,new Rect(0, 0, foregroundBmp.PixelWidth, foregroundBmp.PixelHeight), WriteableBitmapExtensions.BlendMode.ColorKeying);
// Save
Windows.Storage.Pickers.FileSavePicker save = new Windows.Storage.Pickers.FileSavePicker();
save.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
save.DefaultFileExtension = ".gif";
save.FileTypeChoices.Add("GIF", new string[] { ".gif" });
StorageFile filesave = await save.PickSaveFileAsync();
Guid encoderId = Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId;
await WinRTXamlToolkit.Imaging.WriteableBitmapSaveExtensions.SaveToFile(backgroundBmp, filesave, encoderId);
//List<InkStroke> tmp = _inkManager.GetStrokes().ToList();
//tmp.RemoveAt(0);
//RenderStroke(tmp.ElementAt(0), Colors.SkyBlue, 10, 1);
SurfaceImageSource surfaceImageSource = new SurfaceImageSource((int)Rectangle1.ActualWidth, (int)Rectangle1.ActualHeight, true);
ImageBrush brush = new ImageBrush();
brush.ImageSource = image.Source;
Rectangle1.Fill = brush;
}
private void RenderStroke(InkStroke stroke, Color color, double width, double opacity = 1)
{
// Each stroke might have more than one segments
var renderingStrokes = stroke.GetRenderingSegments();
//
// Set up the Path to insert the segments
var path = new Windows.UI.Xaml.Shapes.Path();
path.Data = new PathGeometry();
((PathGeometry)path.Data).Figures = new PathFigureCollection();
var pathFigure = new PathFigure();
pathFigure.StartPoint = renderingStrokes.First().Position;
((PathGeometry)path.Data).Figures.Add(pathFigure);
//
// Foreach segment, we add a BezierSegment
foreach (var renderStroke in renderingStrokes)
{
pathFigure.Segments.Add(new BezierSegment()
{
Point1 = renderStroke.BezierControlPoint1,
Point2 = renderStroke.BezierControlPoint2,
Point3 = renderStroke.Position
});
}
// Set the general options (i.e. Width and Color)
path.StrokeThickness = width;
path.Stroke = new SolidColorBrush(color);
// Opacity is used for highlighter
path.Opacity = opacity;
funnyCanvas.Children.Add(path);
}
}
}
You put the content in a Viewbox, which will stretch it. You need to calculate the on-screen coordinates of your rectangle.
Give this a try.
var scalex = MyViewbox.GetScaleChildX();
var scaley = MyViewbox.GetScaleChildY();
SurfaceImageSource surfaceImageSource = new SurfaceImageSource((int)(scalex * Rectangle1.ActualWidth), (int)(scaley * Rectangle1.ActualHeight), true);
public static double GetChildScaleX(this Viewbox viewbox)
{
if (viewbox.Child == null)
throw new InvalidOperationException("Can't tell effective scale of a Viewbox child for a Viewbox with no child.");
var fe = viewbox.Child as FrameworkElement;
if (fe == null)
throw new InvalidOperationException("Can't tell effective scale of a Viewbox child for a Viewbox with a child that is not a FrameworkElement.");
if (fe.ActualWidth == 0)
throw new InvalidOperationException("Can't tell effective scale of a Viewbox child for a Viewbox with a child that is not laid out.");
return viewbox.ActualWidth / fe.ActualWidth;
}
GetChildScaleY is the same, but with Heights (taken from here).
(Make sure you name your Viewbox)
<Viewbox x:Name="MyViewbox">

Custom UserControl not showing up in ListBox

I have a problem displaying custom UserControls in my ListBox programmatically. I just can't seem to figure out what is wrong. The list-item shows up without image or text.
My project consists of:
MainWindow.xaml
MainWindow.xaml.cs
cvMenuItem.xaml
cvMenuItem.xaml.cs
Code of MainWindow.xaml.cs
private void cvMenuItem_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
{
lstContacts.Items.Clear();
cvMenuItem test = new cvMenuItem("test",
Environment.GetEnvironmentVariable("USERPROFILE") + #"\Downloads\images.jpg");
lstContacts.Items.Add(test);
}
Code of cvMenuItem.xaml.cs
public partial class cvMenuItem : UserControl
{
public cvMenuItem()
{
InitializeComponent();
}
public cvMenuItem(string text, string Logo)
{
this.Height = 50;
this.Width = 186;
txtService = new TextBlock() { Width = 100, Height = 50 };
imgLogo = new Image() { Width = 50, Height = 50 };
//Just found out, adding the objects as childeren partially works
this.AddChild(imgLogo);
//But I can't add txtService as Childeren
//this.AddChild(txtService);
this.Services = text;
this.Logo = Logo;
}
public string Services
{
get{ return txtService.Text.ToString() }
set
{
txtService.Text = value;
}
}
public string Logo
{
get{ return imgLogo.Source.ToString(); }
set
{
var uriSource = new Uri(value);
imgLogo.Source = new BitmapImage(uriSource);
}
}
My cvMenuItem.xaml.cs
<UserControl x:Class="WpfApplication1.cvMenuItem"
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"
mc:Ignorable="d" Height="50" Width="186">
<Grid Width="186" VerticalAlignment="Top">
<Image Name="imgLogo" Height="50" Width="50" HorizontalAlignment="Left" VerticalAlignment="Top" OpacityMask="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}" />
<TextBlock Name="txtService" HorizontalAlignment="Left" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Bottom" Height="18" Width="121" Margin="70,0,0,18" RenderTransformOrigin="0.499,1.932"/>
</Grid>
</UserControl>
First of all you need to call InitializeComponent in the custom constructor you have added, as that is needed to process the XAML properly. Otherwise all the controls you add in the XAML will be null when running the application.
Additionally it makes no sense to create the TextBlock and Image again in the code-behind. You just have to use the ones created in the XAML.
So to get it working, change the code in the constructor to the following:
public cvMenuItem(string text, string Logo)
{
InitializeComponent();
this.Height = 50;
this.Width = 186;
this.Services = text;
this.Logo = Logo;
}

Error when i use storyboard in windows phone 8?

I'm working on a Windows Phone app and i create storyboard that changes position an image.But i have an error.
An exception of type 'System.InvalidOperationException' occurred in System.Windows.ni.dll but was not handled in user code storyboard
This is my code:
XAML:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" MouseMove="Mouse_Move">
<Grid.Resources>
<Storyboard x:Name="sbimg">
<PointAnimation x:Name="animationimg" Duration="0:0:0.1"
Storyboard.TargetName="earimg" />
</Storyboard>
</Grid.Resources>
<Image x:Name="earimg" Height="30" Width="30"
Source="1.png" Margin="0,0,426,577">
</Image>
</Grid>
And C#:
private void Mouse_Move(object sender, System.Windows.Input.MouseEventArgs e)
{
double pointX = e.GetPosition(null).X;
double pointY = e.GetPosition(null).Y;
Point mypoint = new Point(pointX,pointY);
animationimg.To = mypoint;
sbimg.Begin();
}
To accomplish this task I suggest to use a Canvas as LayoutRoot and a GestureListner from Windows Phone Toolkit to catch user gestures. Your XAML should looks like this
<Canvas x:Name="LayoutRoot"
Background="Transparent">
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener
x:Name="SurfaceGestureListner"
Tap="SurfaceGestureListner_OnTap"
DragDelta="GestureListnerDragDelta"/>
</toolkit:GestureService.GestureListener>
<Image
x:Name="MyImage"
Source="/Assets/ApplicationIcon.png" Height="100" Width="100">
<Image.RenderTransform>
<TranslateTransform x:Name="TranslateTransform"/>
</Image.RenderTransform>
</Image>
</Canvas>
And in code behind
private Storyboard GenerateMoveAnimation(double x, double y)
{
var xAnimation = new DoubleAnimation
{
From = TranslateTransform.X,
To = x
};
var yAnimation = new DoubleAnimation
{
From = TranslateTransform.Y,
To = y
};
Storyboard.SetTarget(xAnimation, TranslateTransform);
Storyboard.SetTargetProperty(xAnimation, new PropertyPath("X"));
Storyboard.SetTarget(yAnimation, TranslateTransform);
Storyboard.SetTargetProperty(yAnimation, new PropertyPath("Y"));
var str = new Storyboard();
str.Children.Add(xAnimation);
str.Children.Add(yAnimation);
return str;
}
private void GestureListnerDragDelta(object sender, DragDeltaGestureEventArgs e)
{
var point = e.GetPosition(LayoutRoot);
GenerateMoveAnimation(point.X, point.Y).Begin();
}
private void SurfaceGestureListner_OnTap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
{
var point = e.GetPosition(LayoutRoot);
GenerateMoveAnimation(point.X, point.Y).Begin();
}

Categories

Resources