TranslateTransform on an IXRPolyline?
I have an application with its main function being charting/graphing. To achieve this, the graph has been implemented using Polylines and the values for polyline points are calculated in the C++ source code. Likewise, we also perform the shifting
in the c++ source code. The issue with this is that multiple for loops are used to go through the index of data points we have on the screen, and this is up to 800 points, so the for loop potentially runs for many cpu cycles, becoming very inefficient.
I wanted to understand if and or how it would be possible to replace the shifting algorithm in the C++ code with XAML TranslateTransform method. I would imagine it would be fairly simple since I shift only each point 1 point over at a time and add
a new point into the front. However, i am not an expert or that familiar coding in XAML so i would not know where to start.
Here is the polyline XAML implementation:
<Polyline x:Name="Graph1" Stroke="#FF8FB349" StrokeThickness="3" Grid.ColumnSpan="5" Grid.RowSpan="5" Points="0,0 1,1"/>
<Polyline x:Name="Graph2" Stroke="#FFDBAB03" StrokeThickness="3" Grid.ColumnSpan="5" Grid.RowSpan="5" Points="0,0 1,1"/>
<Polyline x:Name="Graph3" Stroke="#FF8263A6" StrokeThickness="3" Grid.ColumnSpan="5" Grid.RowSpan="5" Points="0,0 1,1"/>
<Polyline x:Name="Graph4" Stroke="#FF77A6DE" StrokeThickness="3" Grid.ColumnSpan="5" Grid.RowSpan="5" Points="0,0 1,1"/>
Very straightforward implementation. Like i said, i only shift 1 point along the X-axis as well as the Y-axis, so can anyone give some guidance if this is possible to do with TranslateTransform so that it is continuously shifting my polyline?
Thanks in advance,
Can you clarify what you mean?
If you're seeing multiple wifi networks as well as yours, that's normal. It will display any networks within range. It doesn't mean you're connected to them or that they're on your network.
Matt
Similar Messages
-
How to use translatetransform and rotatetransform on Canvas
Hi,
Used TransalateTransform and Rotatetransform on canvas individually using ManipulationMode.
How to apply, both TransalateTransform and Rotatetransform on canvas Concurrently in Windows Store App.
Regards,
ChakradharThis is the wpf forum rather than windows store app forum.
It is in your own interest to ask questions in a forum where the most developers who work on your technology of interest are likely to be reading questions.
https://social.msdn.microsoft.com/Forums/windowsapps/en-us/home?category=windowsapps
I suggest when you post there you also explain your requirement more.
EG
Is this in code, xaml, are you considering binding values, is it the children of the canvas or the canvas itself?
What end result are you hoping to achieve?
Without understanding those I would have to guess what you mean.
I should think it's pretty similar to wpf.
A translatetransform is about moving stuff round and you would apply it in xaml like:
http://www.c-sharpcorner.com/uploadfile/mahesh/translatetransform-in-wpf/
<Rectangle Width="200" Height="50" Fill="Yellow" Margin="61,27,117,184" />
<Rectangle Width="200" Height="50" Fill="Blue" Opacity="0.5" Margin="59,101,119,110">
<Rectangle.RenderTransform>
<TranslateTransform X="50" Y="20" />
</Rectangle.RenderTransform>
</Rectangle>
A rotatetransform is about rotating something.
http://www.codeproject.com/Articles/14895/WPF-Tutorial-Part-Transformations
<ListBox Name="listBox1" FontSize="15"
Canvas.Bottom="140" Canvas.Left="30"
Canvas.Right="150" Canvas.Top="40">
<ListBoxItem IsSelected="True">Canada</ListBoxItem>
<ListBoxItem>Spain</ListBoxItem>
<ListBox.RenderTransform> *(1)*
<RotateTransform Angle="-20"
CenterX="50" CenterY="50" /> *(2)*
</ListBox.RenderTransform>
</ListBox>
You do multiple transforms using a transformgroup
https://msdn.microsoft.com/en-us/library/ms750975%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
And you can bind those values to properties of a viewmodel or a dynamicresource.
This might, of course, be slightly different in windows store apps.
Hope that helps.
Recent Technet articles:
Property List Editing ;
Dynamic XAML -
A proper solution to a WPF application using On Screen Keyboard
Hi.
I´ve been working for some time on a good OSK solution for my WPF apps, that are running on a tablet. But it´s hard working with the OSK.exe and tabtip.exe, because of several bugs, strange behaviour and no standardized solution to this ordinary problem.
What I (probably) need is a custom textbox control, which inherits from System.Windows.Controls.TextBox, and overrides some methods.
The simple requirements for this textbox should be:
1. When a user clicks in a textfield, the tabtip.exe (or alike) keyboard should pop up at the bottom of the screen (default).
2. If the keyboard pops up on top of the textbox, the contentframe should scroll so that the textbox is visible.
3. When the textbox loses focus, the keyboard should close automatically, except if the user clicks on another textbox.
This seems like pretty standard behaviour right? Well I´ve looked a long time for solutions (there is no standard microsoft way which is kind of weird), and as said I´ve tried making my own but with no luck. For example, sometimes when I try to kill the process,
it fails. When I click the close button in the upperright corner on the keyboard, like 5-6-7 times, it closes. The behaviour from PC to tablet is not consistent. The ScrollViewer.ScrollToVerticalOffset(x); sometimes doesent work on a tablet, and so on.
So does any of you know a good solution to this common problem?Hello Farsen.
I have been creating a Win8 app for my business and in learning that I discovered they have "LayoutAware" pages. The basic idea behind the LayoutAware page is that they move the page up when the keyboard is active and that different layouts
can be set for the tablet orientation.
You could apply the same basic concept to WPF using VisualStateManager.
Here is a real quick example....
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
x:Class="WpfApplication27.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Grid x:Name="LayoutRoot">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="VisualStateGroup">
<VisualStateGroup.Transitions>
<VisualTransition GeneratedDuration="0:0:0.2"/>
</VisualStateGroup.Transitions>
<VisualState x:Name="KeyboardOpen">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="grid">
<EasingDoubleKeyFrame KeyTime="0" Value="-130"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="KeyboardClosed"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<VisualStateManager.CustomVisualStateManager>
<ei:ExtendedVisualStateManager/>
</VisualStateManager.CustomVisualStateManager>
<Grid x:Name="grid" HorizontalAlignment="Center" Height="41.92" VerticalAlignment="Center" Width="200" RenderTransformOrigin="0.5,0.5">
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Grid.RenderTransform>
<TextBox TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
<Button Content="Button" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="75"/>
</Grid>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApplication27
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
public MainWindow()
this.InitializeComponent();
// Insert code required on object creation below this point.
private void TextBox_GotFocus(object sender, System.Windows.RoutedEventArgs e)
Process.Start("TabTip.exe");
VisualStateManager.GoToElementState(LayoutRoot, "KeyboardOpen", true);
private void TextBox_LostFocus(object sender, System.Windows.RoutedEventArgs e)
Process[] processlist = Process.GetProcesses();
foreach(Process process in processlist)
if (process.ProcessName == "TabTip")
process.Kill();
VisualStateManager.GoToElementState(LayoutRoot, "KeyboardClosed", true);
break;
Now, I'm sure folks get right tired of my shouting Blend. But... if you have Blend you could make short work of setting this up.
If you open your project in Blend, select the xaml page with the design view showing.
Select the "States" tab.
Click the "Add State" button and you can double click the state that appears to rename it or rename it directly in xaml.
Change the Transition Duration if desired.
Select the state and you will see that "State Recording" is active.
Just move your items where you want them for that state.
I hope that gives you some ideas.
~Christine
Edit. The red ellipse in the image above circles the "Add State" button. -
Windows Phone camera App crash when switching to another page
I am creating a Simple Face Detection App for Windows Phone in C#. I turn on my camera , everything works perfect and FaceDetector works too, but when I try to navigate to other page my App always crashes and I do not why. I tried to test my App in Windows
Phone Emulator and here the navigation works. I also tried debug my App in real device, but there the method OnNavigatedFrom is never hit.
FaceDetection.xaml.cs
public partial class FaceDetection : PhoneApplicationPage
#region member variables
const string MODEL_FILE = "models/haarcascade_frontalface_alt.xml";
FaceDetector.Detector _detector;
int _downsampleFactor = 2;
private byte[] _pixelDataGray;
private byte[] _pixelDataDownsampled;
private int[] _pixelDataGrayInt;
private WriteableBitmap _wb;
private DateTime _lastUpdate;
public static int pocet = 5;
double point1;
double point2;
double heightRectangle;
double widthRectangle;
#endregion
public FaceDetection()
InitializeComponent();
_detector = new FaceDetector.Detector(XDocument.Load(MODEL_FILE));
private void NewCameraFrame(object sender, CameraFrameEventArgs cameraFrameEventArgs)
PageOrientation orientaciaObrazovky = ((PhoneApplicationFrame)Application.Current.RootVisual).Orientation;
cameraViewer.UpdateOrientation(orientaciaObrazovky);
var w = cameraViewer.CameraWidth;
var h = cameraViewer.CameraHeight;
if (_pixelDataGray == null || _pixelDataGray.Length != h * w)
_pixelDataGray = new byte[w / _downsampleFactor * h / _downsampleFactor];
_pixelDataDownsampled =
new byte[w / _downsampleFactor * h / _downsampleFactor];
_pixelDataGrayInt = new int[w / _downsampleFactor * h / _downsampleFactor];
_wb = new WriteableBitmap(w / _downsampleFactor, w / _downsampleFactor);
_lastUpdate = DateTime.Now;
Utils.DownSample(cameraFrameEventArgs.ARGBData, w, h, ref _pixelDataGrayInt, _downsampleFactor);
Utils.ARGBToGreyScale(_pixelDataGrayInt, ref _pixelDataGray);
Utils.HistogramEqualization(ref _pixelDataGray);
Utils.GrayToARGB(_pixelDataGray, ref _pixelDataGrayInt);
List<FaceDetector.Rectangle> faces = new List<FaceDetector.Rectangle>();
if (orientaciaObrazovky == PageOrientation.PortraitUp || orientaciaObrazovky == PageOrientation.PortraitDown)
int scalw = w / _downsampleFactor;
int scalh = h / _downsampleFactor;
int[] _pixelDataGrayIntRotated = new int[scalw * scalh];
for (int x = 0; x < scalw; x++)
for (int y = 0; y < scalh; y++)
_pixelDataGrayIntRotated[y + x * scalh] = _pixelDataGrayInt[x + y * scalw];
faces = _detector.getFaces(
_pixelDataGrayIntRotated,
h / _downsampleFactor,
w / _downsampleFactor,
2f, 1.25f, 0.1f, 1, false, false); // height-width swapped
else
faces = _detector.getFaces(
_pixelDataGrayInt,
w / _downsampleFactor,
h / _downsampleFactor,
2f, 1.25f, 0.1f, 1, false, false);
var elapsed = (DateTime.Now - _lastUpdate).TotalMilliseconds;
_pixelDataGrayInt.CopyTo(_wb.Pixels, 0);
_wb.Invalidate();
Dispatcher.BeginInvoke(delegate()
cnvsFaceRegions.Children.Clear();
foreach (var r in faces)
System.Windows.Shapes.Rectangle toAdd = new System.Windows.Shapes.Rectangle();
TranslateTransform loc = new TranslateTransform();
if (orientaciaObrazovky == PageOrientation.PortraitUp)
loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth;
loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight;
point1 = r.X;
point2 = r.Y;
else if (orientaciaObrazovky == PageOrientation.PortraitDown)
loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth;
loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight;
point1 = r.X;
point2 = r.Y;
else if (orientaciaObrazovky == PageOrientation.LandscapeLeft)
loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth - 50;
loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight + 90;
point1 = r.X;
point2 = r.Y;
else if (orientaciaObrazovky == PageOrientation.LandscapeRight)
loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth+50 ;
loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight -90;
point1 = r.X;
point2 = r.Y;
toAdd.RenderTransform = loc;
toAdd.Width = r.Width * _downsampleFactor + 50;
toAdd.Height = r.Height * _downsampleFactor + 50;
toAdd.Stroke = new SolidColorBrush(Colors.Red);
cnvsFaceRegions.Children.Add(toAdd);
widthRectangle = toAdd.Width;
heightRectangle = toAdd.Height;
point1 = (loc.X);
point2 = (loc.Y);
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
base.OnNavigatedTo(e);
cameraViewer.SaveToCameraRoll = true;
cameraViewer.NewCameraFrame += NewCameraFrame;
cameraViewer.StartPumpingFrames();
CameraButtons.ShutterKeyHalfPressed += OnButtonHalfPress;
CameraButtons.ShutterKeyPressed += OnButtonFullPress;
CameraButtons.ShutterKeyReleased += OnButtonRelease;
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
base.OnNavigatedFrom(e);
cameraViewer.StopPumpingFrames();
CameraButtons.ShutterKeyHalfPressed -= OnButtonHalfPress;
CameraButtons.ShutterKeyPressed -= OnButtonFullPress;
CameraButtons.ShutterKeyReleased -= OnButtonRelease;
private void OnButtonHalfPress(object sender, EventArgs e)
cameraViewer.NewCameraFrame -= NewCameraFrame;
private void OnButtonFullPress(object sender, EventArgs e)
SaveScreenShots();
private void OnButtonRelease(object sender, EventArgs e)
cameraViewer.NewCameraFrame += NewCameraFrame;
private static WriteableBitmap CropImage(WriteableBitmap source, int xOffset, int yOffset, int width, int height)
var sourceWidth = source.PixelWidth;
var result = new WriteableBitmap(width, height);
for (var x = 0; x <= height - 1; x++)
var sourceIndex = xOffset + (yOffset + x) * sourceWidth;
var destinationIndex = x * width;
Array.Copy(source.Pixels, sourceIndex, result.Pixels, destinationIndex, width);
return result;
private void SaveScreenShots()
string namePerson = PhoneApplicationService.Current.State["TextBoxValue"] as String;
bool b = cnvsFaceRegions.Children.Any();
cnvsFaceRegions.Children.Clear();
if (!b)
MessageBox.Show("No face detected ");
else
for (int j = 1; j <= pocet; j++)
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
var bmp = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
bmp.Render(this, null);
byte[] bb = EncodeToJpeg(bmp);
bmp.Invalidate();
WriteableBitmap bmp2 = CropImage(bmp, (int)point1, (int)point2, (int)widthRectangle, (int)heightRectangle);
using (var isoFileStream = isoStore.CreateFile(namePerson + j))
System.Windows.Media.Imaging.Extensions.SaveJpeg(bmp2, isoFileStream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
isoFileStream.Close();
MessageBox.Show("Saved successfully " + pocet + " images");
cameraViewer.NewCameraFrame += NewCameraFrame;
public byte[] EncodeToJpeg(WriteableBitmap wb)
using (MemoryStream stream = new MemoryStream())
wb.SaveJpeg(
stream,
wb.PixelWidth,
wb.PixelHeight,
0,
85);
return stream.ToArray();
private void cameraViewer_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
cameraViewer.NewCameraFrame -= NewCameraFrame;
private void cameraViewer_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
SaveScreenShots();
private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
NavigationService.Navigate(new Uri("/PersonAndGallery;component/Gallery.xaml", UriKind.Relative));
CameraViewer.cs
public class CameraFrameEventArgs : RoutedEventArgs
public int[] ARGBData { get; set; }
public static class AppGlobal
public static bool isPortrait = true;
public class CameraViewer : Grid
#region Events
public EventHandler<CameraFrameEventArgs> NewCameraFrame { get; set; }
public EventHandler<ContentReadyEventArgs> NewCameraCaptureImage { get; set; }
public EventHandler<CameraOperationCompletedEventArgs> CamInitialized { get; set; }
#endregion
#region Properties
public int CameraWidth
get { return _cameraWidth; }
set { _cameraWidth = value; }
public int CameraHeight
get { return _cameraHeight; }
set { _cameraHeight = value; }
public bool PhotoOnPress
get { return _photoOnPress; }
set
_photoOnPress = value;
// CameraButtons.ShutterKeyPressed -= CameraButtonsOnShutterKeyPressed;
if (_photoOnPress)
// CameraButtons.ShutterKeyPressed += CameraButtonsOnShutterKeyPressed;
public bool SaveToCameraRoll { get; set; }
public PhotoCamera Camera
get { return _camera; }
public bool TakingPhoto
get { return _takingPhoto; }
#endregion
#region Member Variables
private PhotoCamera _camera; // the windows phone camera that takes the photos
private int _cameraWidth = -1;
private int _cameraHeight = -1;
private Thread _pumpFramesThread;
private static ManualResetEvent _pauseFramesEvent = new ManualResetEvent(true);
private bool _takingPhoto;
VideoBrush viewfinderBrush;
private bool _photoOnPress;
private SoundEffect _cameraShutterSound;
private static ManualResetEvent _cameraCaptureEvent = new ManualResetEvent(true);
private static ManualResetEvent _cameraInitializedEvent = new ManualResetEvent(false);
private bool _pumpFrames;
#endregion
#region Constructor
public CameraViewer()
Unloaded += new RoutedEventHandler(OnUnloaded);
PhotoOnPress = true;
public override void OnApplyTemplate()
base.OnApplyTemplate();
#endregion
#region Public methods
public void StartPumpingFrames()
_pauseFramesEvent = new ManualResetEvent(true);
_cameraCaptureEvent = new ManualResetEvent(true);
_cameraInitializedEvent = new ManualResetEvent(false);
InitializeCamera();
_pumpFrames = true;
if (_pumpFramesThread == null)
_pumpFramesThread = new Thread(PumpFrames);
if (!_pumpFramesThread.IsAlive)
_pumpFramesThread.Start();
public void StopPumpingFrames()
_pumpFrames = false;
_pumpFramesThread = null;
Camera.Dispose();
public void TakePhoto()
if (TakingPhoto)
return;
_cameraCaptureEvent.Reset();
FrameworkDispatcher.Update();
_cameraShutterSound.Play();
_takingPhoto = true;
Camera.CaptureImage();
#endregion
private void CameraButtonsOnShutterKeyPressed(object sender, EventArgs eventArgs)
if (_photoOnPress && !TakingPhoto)
_cameraCaptureEvent.WaitOne();
TakePhoto();
private void OnUnloaded(object sender, RoutedEventArgs e)
_cameraInitializedEvent.Reset();
public void InitializeCamera()
_cameraInitializedEvent.Reset();
// Check to see if the camera is available on the device.
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))
// Initialize the default camera.
_camera = new Microsoft.Devices.PhotoCamera();
//Event is fired when the PhotoCamera object has been initialized
Camera.Initialized +=
new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(CameraInitialized);
Camera.CaptureImageAvailable += CameraOnCaptureImageAvailable;
Camera.CaptureCompleted += CameraOnCaptureCompleted;
//Set the VideoBrush source to the camera
// var viewfinderBrush = new VideoBrush();
viewfinderBrush = new VideoBrush();
viewfinderBrush.Stretch = Stretch.Fill;
viewfinderBrush.RelativeTransform = new CompositeTransform { CenterX = 0.5, CenterY = 0.5 };
viewfinderBrush.SetSource(Camera);
System.Windows.Shapes.Rectangle rect = new System.Windows.Shapes.Rectangle();
rect.Fill = viewfinderBrush;
this.Children.Add(rect);
Stream stream = TitleContainer.OpenStream("models/shutter.wav");
_cameraShutterSound = SoundEffect.FromStream(stream);
// CameraButtons.ShutterKeyPressed -= CameraButtonsOnShutterKeyPressed;
if (_photoOnPress)
// CameraButtons.ShutterKeyPressed += CameraButtonsOnShutterKeyPressed;
else
// The camera is not supported on the device.
MessageBox.Show(
"Sorry, this sample requires a phone camera and no camera is detected. This application will not show any camera output.");
private void CameraOnCaptureCompleted(object sender, CameraOperationCompletedEventArgs cameraOperationCompletedEventArgs)
_cameraCaptureEvent.Set();
_takingPhoto = false;
private void CameraOnCaptureImageAvailable(object sender, ContentReadyEventArgs contentReadyEventArgs)
if (SaveToCameraRoll)
Dispatcher.BeginInvoke(() =>
WriteableBitmap bitmap =
CreateWriteableBitmap(contentReadyEventArgs.ImageStream,
(int)Camera.Resolution.Width,
(int)Camera.Resolution.Height);
// SaveCapturedImage(bitmap);
//TakeScreenShots();
if (NewCameraCaptureImage != null)
NewCameraCaptureImage.Invoke(this, contentReadyEventArgs);
// Helper for CameraOnCaptureImageAvailable
private void SaveCapturedImage(WriteableBitmap imageToSave)
var stream = new MemoryStream();
imageToSave.SaveJpeg(stream, imageToSave.PixelWidth, imageToSave.PixelHeight, 0, 100);
//Take the stream back to its beginning because it will be read again
//when saving to the library
stream.Position = 0;
var library = new MediaLibrary();
string fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss}.jpg", DateTime.Now);
library.SavePictureToCameraRoll(fileName, stream);
//save to Save Photo
Picture pic;
private void TakeScreenShots()
WriteableBitmap bmp = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
bmp.Render(this, null);
byte[] bb = EncodeToJpeg(bmp);
bmp.Invalidate();
MemoryStream mem = new MemoryStream();
bmp.SaveJpeg(mem, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
mem.Seek(0, System.IO.SeekOrigin.Begin);
if (mem != null)
MediaLibrary library = new MediaLibrary();
try
pic = library.SavePicture("Mask_" + Guid.NewGuid().ToString(), mem);
MessageBox.Show("Your picture is now accessible through the Saved Picture album.", "Saved successfully.", MessageBoxButton.OK);
catch (Exception ex)
MessageBox.Show("Unable to save the photo." + ex);
public byte[] EncodeToJpeg(WriteableBitmap wb)
using (MemoryStream stream = new MemoryStream())
wb.SaveJpeg(
stream,
wb.PixelWidth,
wb.PixelHeight,
0,
85);
return stream.ToArray();
// Creates a WriteableBitmap from an imageStream
private WriteableBitmap CreateWriteableBitmap(Stream imageStream, int width, int height)
var bitmap = new WriteableBitmap(width, height);
imageStream.Position = 0;
bitmap.LoadJpeg(imageStream);
return bitmap;
private void CameraInitialized(object sender, CameraOperationCompletedEventArgs e)
if (e.Succeeded)
try
// available resolutions are ordered based on number of pixels in each resolution
CameraWidth = (int)Camera.PreviewResolution.Width;
CameraHeight = (int)Camera.PreviewResolution.Height;
if (CamInitialized != null)
CamInitialized.Invoke(this, e);
_cameraInitializedEvent.Set();
_pauseFramesEvent.Set();
catch (ObjectDisposedException)
// If the camera was disposed, try initializing again
private void PumpFrames()
_cameraInitializedEvent.WaitOne();
int[] pixels = new int[CameraWidth * CameraHeight];
int numExceptions = 0;
while (_pumpFrames)
_pauseFramesEvent.WaitOne();
_cameraCaptureEvent.WaitOne();
_cameraInitializedEvent.WaitOne();
try
Camera.GetPreviewBufferArgb32(pixels);
catch (Exception e)
// If we get an exception try capturing again, do this up to 10 times
if (numExceptions >= 10)
throw e;
numExceptions++;
continue;
numExceptions = 0;
_pauseFramesEvent.Reset();
Deployment.Current.Dispatcher.BeginInvoke(
() =>
if (NewCameraFrame != null && _pumpFrames)
NewCameraFrame(this, new CameraFrameEventArgs { ARGBData = pixels });
_pauseFramesEvent.Set();
//na zmenu orientacie
public void UpdateOrientation(PageOrientation orientation)
if (orientation == PageOrientation.PortraitDown)
viewfinderBrush.RelativeTransform =
new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = 270 };
/* else if (orientation == PageOrientation.PortraitDown && cameraType == 2)
viewfinderBrush.RelativeTransform =
new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
else if (orientation == PageOrientation.PortraitUp && cameraType == 2)
viewfinderBrush.RelativeTransform =
new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = -90 };
else if (orientation == PageOrientation.PortraitUp)
viewfinderBrush.RelativeTransform =
new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation =90 };
else if (orientation == PageOrientation.LandscapeLeft)
viewfinderBrush.RelativeTransform =
new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = 0 };
else if (orientation == PageOrientation.LandscapeRight)
viewfinderBrush.RelativeTransform =
new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = -180 };
Thanks for reply.Hi Facko,
Thanks for posting at the forum, however it could be really difficult for us to copy/paste your code and try to repro the issue, I would suggest you to provide a repro sample for us so that we can debug for you.
And base on your description, looks like your app only crashes on the real device, but not on the emulator. I have question here, how the app works on the emulator?
As I know if we open the camera on emulator, the only thing we can see is kind of small color blocks instead of the real images.
You could also try to close the camera and then dispose the object to see if it works.
--James
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Why can't I change the color of my ProgressBar? Always green.
I added a ProgressBar object to my form. Works fine. But the bar is always green despite setting the Forecolor to Blue in the Design and to red in code:
' intTotalNumberOfFiles = 80
pgbCloset.Value = 0
pgbCloset.Step = 1
pgbCloset.Maximum = 99
pgbCloset.ForeColor = Color.Red ' for testing.
For intCnt = 1 To intTotalNumberOfFiles
'If intTotalNumberOfFiles > 0 Then pgbCloset.ForeColor = Color.Green
'If intTotalNumberOfFiles > 30 Then pgbCloset.ForeColor = Color.Yellow
'If intTotalNumberOfFiles > 60 Then pgbCloset.ForeColor = Color.Red
pgbCloset.PerformStep()
Next
Any idea why? How do I fix this? Thx.... ups, VB,so here's something to start with... (or uncheck the "enable XP visual styles" checkBox in your project's settings)
Partial Public Class Form1
Inherits Form
Private WithEvents progressBar1 As New NewProgressBar()
Private WithEvents button1 As New System.Windows.Forms.Button()
Private WithEvents timer1 As New System.Windows.Forms.Timer()
Private WithEvents button2 As New System.Windows.Forms.Button()
Private WithEvents trackBar1 As New TrackBar()
Private WithEvents trackBar2 As New TrackBar()
Public Sub New()
InitializeComponent()
Me.button1.Location = New System.Drawing.Point(20, 105)
Me.button1.Name = "button1"
Me.button1.Size = New System.Drawing.Size(75, 23)
Me.button1.TabIndex = 1
Me.button1.Text = "button1"
Me.button1.UseVisualStyleBackColor = True
Me.timer1.Interval = 50
Me.progressBar1.Location = New System.Drawing.Point(41, 1)
Me.progressBar1.Name = "progressBar1"
Me.progressBar1.Size = New System.Drawing.Size(187, 23)
Me.progressBar1.TabIndex = 0
Me.progressBar1.ShowText = True
Me.progressBar1.ForeColor = Color.White
'Colors and Positions
Me.progressBar1.Color1 = Color.Red
Me.progressBar1.Color2 = Color.Yellow
Me.progressBar1.Color3 = Color.Green
'PositionColor2 must be in a range from 0 to 1.0F
Me.progressBar1.PositionColor2 = 0.71F
Me.progressBar1.GammaCorrected = True
'change OverlaySpeed and Delay and Width
Me.progressBar1.OverlayAddAmount = 0.8F
Me.progressBar1.OverlayReshowDelay = 35.0F
Me.progressBar1.OverlayWidth = 50.0F
Me.button2.Location = New System.Drawing.Point(120, 105)
Me.button2.Name = "button2"
Me.button2.Size = New System.Drawing.Size(75, 23)
Me.button2.TabIndex = 2
Me.button2.Text = "button2"
Me.button2.UseVisualStyleBackColor = True
Me.trackBar1.Location = New Point(20, 145)
Me.trackBar1.Width = Me.progressBar1.Width
Me.trackBar1.Minimum = 0
Me.trackBar1.Maximum = 100
Me.trackBar1.Value = 10
Me.trackBar2.Location = New Point(20, 195)
Me.trackBar2.Width = Me.progressBar1.Width
Me.trackBar2.Minimum = 0
Me.trackBar2.Maximum = 100
Me.trackBar2.Value = 30
Me.Controls.Add(Me.button2)
Me.Controls.Add(Me.button1)
Me.Controls.Add(Me.progressBar1)
Me.Controls.Add(Me.trackBar1)
Me.Controls.Add(Me.trackBar2)
Me.progressBar1.Left = 0
Me.progressBar1.Width = Me.ClientSize.Width
End Sub
Private Sub trackBar2_ValueChanged(sender As Object, e As EventArgs) Handles trackBar2.ValueChanged
Me.progressBar1.OverlayReshowDelay = CSng(Me.trackBar2.Value)
End Sub
Private Sub trackBar1_ValueChanged(sender As Object, e As EventArgs) Handles trackBar1.ValueChanged
Me.progressBar1.OverlayAddAmount = CSng(Me.trackBar1.Value) / 10.0F
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
Me.timer1.Enabled = True
End Sub
Private Sub timer1_Tick(sender As Object, e As EventArgs) Handles timer1.Tick
Me.timer1.Stop()
Me.progressBar1.Value += 0.5F
If Me.progressBar1.Value = Me.progressBar1.Maximum Then
Me.progressBar1.Value = 0
End If
Me.timer1.Start()
End Sub
Private Sub button2_Click(sender As Object, e As EventArgs) Handles button2.Click
Me.timer1.Enabled = False
End Sub
End Class
Public Class NewProgressBar
Inherits ProgressBar
Public Property Percentage() As Single
Get
Return m_Percentage
End Get
Set(value As Single)
m_Percentage = Value
End Set
End Property
Private m_Percentage As Single
Public Property ShowText() As Boolean
Get
Return m_ShowText
End Get
Set(value As Boolean)
m_ShowText = Value
End Set
End Property
Private m_ShowText As Boolean
Private _doMarqueeOverlay As Boolean = False
Private WithEvents timer1 As New Timer()
Private _pos As Single = 0
Private _rWidth As Single = 71
Public Property OverlayWidth() As Single
Get
Return _rWidth
End Get
Set(value As Single)
_rWidth = value
End Set
End Property
Private _c As Integer = 0
Private _posAdd As Single = 1.5F
Public Property OverlayAddAmount() As Single
Get
Return _posAdd
End Get
Set(value As Single)
_posAdd = value
End Set
End Property
Private _posDelay As Single = 50
Public Property OverlayReshowDelay() As Single
Get
Return _posDelay
End Get
Set(value As Single)
_posDelay = value
End Set
End Property
Public Property Color1() As Color
Get
Return m_Color1
End Get
Set(value As Color)
m_Color1 = Value
End Set
End Property
Private m_Color1 As Color
Public Property Color2() As Color
Get
Return m_Color2
End Get
Set(value As Color)
m_Color2 = Value
End Set
End Property
Private m_Color2 As Color
Public Property Color3() As Color
Get
Return m_Color3
End Get
Set(value As Color)
m_Color3 = Value
End Set
End Property
Private m_Color3 As Color
Public Property PositionColor2() As Single
Get
Return m_PositionColor2
End Get
Set(value As Single)
m_PositionColor2 = Value
End Set
End Property
Private m_PositionColor2 As Single
Public Shadows Property Value() As Single
Get
Return Me.Percentage
End Get
Set(value As Single)
Me.Percentage = value
'maybe dont invalidata always...
If Not _doMarqueeOverlay Then
Me.Invalidate()
End If
End Set
End Property
Private m_useImg As Boolean
Public Property UseImg() As Boolean
Get
Return m_useImg
End Get
Set(value As Boolean)
m_useImg = value
End Set
End Property
Private m_image As Bitmap
Public Property Image() As Bitmap
Get
Return m_image
End Get
Set(value As Bitmap)
m_image = value
End Set
End Property
Public Sub New()
Me.SetStyle(ControlStyles.UserPaint, True)
Me.DoubleBuffered = True
Color1 = Color.Lime
Color2 = Color.Green
Color3 = Color.Red
PositionColor2 = 0.55F
End Sub
Public Property GammaCorrected As Boolean
Protected Overrides Sub OnPaint(e As PaintEventArgs)
Dim rec As Rectangle = e.ClipRectangle
rec.Width = CInt(rec.Width * (CDbl(Value) / Maximum)) - 4
If ProgressBarRenderer.IsSupported Then
ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle)
Else
e.Graphics.DrawRectangle(Pens.Gray, 0, 0, Me.Width, Me.Height)
End If
rec.Height = rec.Height - 4
If m_useImg AndAlso Not Image Is Nothing Then
Using t As New TextureBrush(Image)
e.Graphics.FillRectangle(t, 2, 2, rec.Width, rec.Height)
End Using
Else
Using l As New System.Drawing.Drawing2D.LinearGradientBrush(e.ClipRectangle, Color.Green, Color.Red, 0.0F)
Dim lb As New System.Drawing.Drawing2D.ColorBlend()
lb.Colors = New Color() {Color1, Color2, Color3}
lb.Positions = New Single() {0, PositionColor2, 1.0F}
l.InterpolationColors = lb
l.GammaCorrection = Me.GammaCorrected
e.Graphics.FillRectangle(l, 2, 2, rec.Width, rec.Height)
End Using
End If
Using l2 As New System.Drawing.Drawing2D.LinearGradientBrush(e.ClipRectangle, Color.FromArgb(147, 255, 255, 255), Color.FromArgb(0, 255, 255, 255), System.Drawing.Drawing2D.LinearGradientMode.Vertical)
Dim lb As New System.Drawing.Drawing2D.ColorBlend()
lb.Colors = New Color() {Color.FromArgb(40, 255, 255, 255), Color.FromArgb(147, 255, 255, 255), Color.FromArgb(40, 255, 255, 255), Color.FromArgb(0, 255, 255, 255)}
lb.Positions = New Single() {0, 0.12F, 0.39F, 1.0F}
l2.InterpolationColors = lb
l2.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile
e.Graphics.FillRectangle(l2, 2, 2, rec.Width, rec.Height)
End Using
If Me.ShowText Then
Using sb As New SolidBrush(Me.ForeColor)
Dim sz As SizeF = e.Graphics.MeasureString(Percentage.ToString("N0") + " %", Me.Font)
e.Graphics.DrawString(Percentage.ToString("N0") + " %", Me.Font, sb, New PointF((Me.Width - sz.Width) / 2.0F, (Me.Height - sz.Height) / 2.0F))
End Using
End If
If Value > 0 AndAlso _doMarqueeOverlay = False Then
StartMarquee()
End If
If Value = Maximum - 1 Then
StopMarquee()
End If
If _doMarqueeOverlay Then
Dim rWidth As Single = _rWidth
If rec.Width < rWidth Then
rWidth = rec.Width
End If
If rWidth + _pos > rec.Width Then
rWidth = rec.Width - _pos
End If
Using l As New System.Drawing.Drawing2D.LinearGradientBrush(New RectangleF(_pos + 2, 2, _rWidth, rec.Height), Color.FromArgb(127, 255, 255, 255), Color.FromArgb(0, 255, 255, 255), System.Drawing.Drawing2D.LinearGradientMode.Horizontal)
Dim lb As New System.Drawing.Drawing2D.Blend()
lb.Factors = New Single() {1, 0, 1}
lb.Positions = New Single() {0, 0.5F, 1.0F}
l.Blend = lb
'l.TranslateTransform(_pos - rWidth, 0);
l.WrapMode = System.Drawing.Drawing2D.WrapMode.TileFlipXY
e.Graphics.FillRectangle(l, _pos + 2, 2, rWidth, rec.Height)
_pos += _posAdd
If _pos >= rec.Width Then
If _c < _posDelay Then
_pos -= _posAdd
_c += 1
Else
_pos = -_rWidth - _posDelay
_c = 0
End If
End If
End Using
End If
End Sub
Private Sub StopMarquee()
timer1.Stop()
_doMarqueeOverlay = False
End Sub
Private Sub StartMarquee()
_doMarqueeOverlay = True
timer1.Interval = 10
timer1.Start()
End Sub
Private Sub timer1_Tick(sender As Object, e As EventArgs) Handles timer1.Tick
timer1.Stop()
Invalidate()
timer1.Start()
End Sub
Protected Overrides Sub Dispose(disposing As Boolean)
If timer1.Enabled Then
timer1.Stop()
End If
timer1.Dispose()
If Not Image Is Nothing Then
Image.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
End Class
Regards,
Thorsten -
Are you drawing text at an angle with TextRenderer?
This is a question for folks that are aware of the difference in quality of output between TextRenderer.DrawText and (Graphics.DrawString + Graphics.TextRenderingHint = Text.TextRenderingHint.AntiAlias). It is an issue that has been discussed by others,
elsewhere, without resolution, and I'm simply asking if anyone has come up with a workaround.
I want to render text in the quality of TextRenderer.DrawText, at right angles or upside down. TextFormatFlags.PreserveGraphicsTranslateTransform ignores calls to RotateTransform on the Graphics object that exposes IDeviceContext to DrawText, and DrawText doesn't
play nicely with bitmaps.
Has anyone figured out a way to draw text at the same quality provided by TextRenderer.DrawText, at an angle other than 0 degrees?
(For those who need a back story to prove to you that I cannot use a Label or Graphics.DrawString for this, here you go.
There is a cat stuck in a tree in my back yard. I would like to rescue him, but there is a troll standing between me and the tree. He's a nasty troll, but on TV he plays a happy-go-lucky helpful troll, so when I call the police to complain, they just laugh
at me. "Ha! You can't fool us! We watch TV!"
The troll will allow me to reach the cat if I provide him with a UserControl that renders text at the same quality as the Windows.Forms.Label control, but at angles 90, 180 and -90 degrees. He is a clever troll in that he notices details between shoddy and
neat; rough and smooth; ugly and pretty; cat and honey badger. Therefore, I have not been able to fool him into thinking that ugly text is pretty by asserting that ugly text is pretty. Argh. I dislike this troll.)And this has to do with
Usability Steven's
issue in what fasion and why are you responding to somebody elses issue
Mick Doherty? Or is this just for my information?
La vida loca
Hi Monkey
This was mainly for info, but the OP did question the difference between GDI and GDIPlus methods of drawing rotated text. Your example only provides a GDIPlus method.
GDI does not respect the Graphics objects rotations, but so long as the PreserveGraphicsTranslateTransform flag is set it will respect Translations.
Here's a simple example to highlight the issue:
Public Class Form1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.SetStyle(ControlStyles.ResizeRedraw, True)
End Sub
Private Sub Form1_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim testString As String = "My Test String"
Dim angle As Single = 0
If Me.CheckBox1.Checked Then angle = 180
Using testFont As New Font("Arial", 24, FontStyle.Regular, GraphicsUnit.Point)
Dim rc As Rectangle = Me.ClientRectangle
rc.Offset(0, -24)
Me.DrawRotatedGDIText(e.Graphics, testString, testFont, rc, Color.Red, angle)
rc.Offset(0, 48)
Me.DrawRotatedGDIPlusText(e.Graphics, testString, testFont, rc, Color.Black, angle)
End Using
End Sub
Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged
Me.Invalidate()
End Sub
Private Sub DrawRotatedGDIText(graphics As Graphics, text As String, font As Font, bounds As Rectangle, color As Color, rotation As Single)
Dim sz As Size = TextRenderer.MeasureText(text, font)
Dim centre As Point = bounds.Location
centre.Offset(bounds.Width \ 2, bounds.Height \ 2)
Dim offset As Point = New Point(-sz.Width \ 2, -sz.Height \ 2)
graphics.TranslateTransform(centre.X, centre.Y)
graphics.RotateTransform(rotation)
TextRenderer.DrawText(graphics, text, font, offset, color, TextFormatFlags.PreserveGraphicsTranslateTransform)
graphics.ResetTransform()
End Sub
Private Sub DrawRotatedGDIPlusText(graphics As Graphics, text As String, font As Font, bounds As Rectangle, color As Color, rotation As Single)
Dim sz As Size = graphics.MeasureString(text, font).ToSize
Dim centre As Point = bounds.Location
centre.Offset(bounds.Width \ 2, bounds.Height \ 2)
Dim offset As Point = New Point(-sz.Width \ 2, -sz.Height \ 2)
graphics.TranslateTransform(centre.X, centre.Y)
graphics.RotateTransform(rotation)
Using myBrush As New SolidBrush(color)
graphics.DrawString(text, font, myBrush, offset)
End Using
graphics.ResetTransform()
End Sub
End Class
Here you can see the GDI string (red text) is rendered differently to the GDI Plus string (black text) i.e. the GDI Plus text is longer. Both strings have been rendered to the correct location as set by the graphics transformation:
Here a Rotation to the graphics object has been performed, but the GDi method has totally ignored it:
As a rule, Win32 based controls render with GDI rather than GDI+ and so if we wish to draw a custom control which appears similar to a Win32 based control we need to render with GDI. If you've ever tried to ownerdraw a tabcontrol then you will have noticed
that the text does not always fit on the tabs if we've used GDI+. using GDI the text fits perfectly, but when we side align the tabs the text does not rotate. We can, as the OP has done, draw unrotated text to a bitmap and then rotate the bitmap and this
works well if we have a solid background. If we have a textured background however, this method is not acceptable.
Mick Doherty
http://dotnetrix.co.uk
http://glassui.codeplex.com -
Rotated text not rendering properly
I'm using SSRS 2008 R2 integrated with SharePoint 2010. In Report Builder 3, i have set the text to Rotate270 and it looks fine. When i save file to sharepoint and view it in the browser, the text is no longer properly positioned in the cell, see below.
Is this a bug? does anyone have any suggestions on how to fix this?
Image from Report Builder 3 preview mode (Business Development is rotated 270 and looks fine)
image from Browser - Business development is truncated
Dean MCTS-SQL 2005 Business Intelligence, SharePoint 2010, ConfigurationHello Dean,
This is not supported in Report viewer when you see the same report from application/explorer view..
for this 270 Degree rotation, you will have to write VB code and from that you can easily convert your text to 270 Degree rotation.
from my point of view and RnD, there is only way to convert 270 Degree rotation in reports.
use the following and you will get your answer.
for that,
first Use System.Drawing DLL in your report.
take image object.
MIME Type : JPEG and field : =Code.LoadImage("Your Text", "Total No Of Character")
example : =Code.LoadImage("20CF", "4") OR
example : =Code.LoadImage("20CF", Length("20CF")
and write this following code
Function LoadImage(ByVal sImageText as String,ByVal sImageTextMax as String)
sImageTextMax= sImageTextMax.PadRight(40)
Dim iFontSize As Integer = 10 ‘//Change this as needed
Dim bmpImage As New Drawing.Bitmap(1, 1)
Dim iWidth As Integer = 0
Dim iHeight As Integer = 0
'// Create the Font object for the image text drawing.
Dim MyFont As New Drawing.Font("Arial", iFontSize, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point)
'// Create a graphics object to measure the text's width and height.
'Graphics(MyGraphics = Graphics.FromImage(bmpImage))
Dim MyGraphics As Drawing.Graphics = Drawing.Graphics.FromImage(bmpImage)
'// This is where the bitmap size is determined.
iWidth = MyGraphics.MeasureString(sImageTextMax, MyFont).Width
iHeight = MyGraphics.MeasureString(sImageTextMax, MyFont).Height
'// Create the bmpImage again with the correct size for the text and font.
'bmpImage = New Drawing.Bitmap(bmpImage, New Drawing.Size(iWidth, iHeight))
bmpImage = New Drawing.Bitmap(bmpImage, New Drawing.Size(iHeight, iWidth))
'// Add the colors to the new bitmap.
MyGraphics = Drawing.Graphics.FromImage(bmpImage)
MyGraphics.Clear(Drawing.Color.LightGray)
MyGraphics.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
MyGraphics.TranslateTransform(0, iWidth)
MyGraphics.RotateTransform(270)
MyGraphics.DrawString(sImageText, MyFont, New Drawing.SolidBrush(Drawing.Color.Black), 0, 0)
MyGraphics.Flush()
Dim stream As IO.MemoryStream = New IO.MemoryStream
Dim bitmapBytes As Byte()
'Create bitmap
bmpImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
bitmapBytes = stream.ToArray
stream.Close()
bmpImage.Dispose()
Return bitmapBytes
End Function
20CF
Hope you are clear with this. :) -
i would like to apply animation on control through jquery like toggel between two div (panel etc) using jquery also reply me how to import library in sapui5?
Hi DaveIII,
In my experience, just using Blend is hard to accomplish this requirement, we need to use Animation to make this work.
Please refer to this article:
http://www.codeproject.com/Articles/197132/Simple-WPF-Page-Transitions
The author created a simple library to apply transition animation between pages:
Any here is a simple sample, it controls animation from code behind:
<Storyboard x:Key="slideRightToLeft"
TargetProperty="RenderTransform.(TranslateTransform.X)"
AccelerationRatio=".4"
DecelerationRatio=".4">
<DoubleAnimation Storyboard.TargetName="viewer" Duration="0:0:0.6" From="-300" To="0"/>
<DoubleAnimation Storyboard.TargetName="bordervisual" Duration="0:0:0.6" From="0" To="300"/>
</Storyboard>
Download link: http://1drv.ms/1BfUzOB
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Horizontal text positioning of DrawString method
I am trying to reproduce the below XPS XAML using the GDI+:
<FixedPage xmlns="http://schemas.microsoft.com/xps/2005/06" xmlns:x="http://schemas.microsoft.com/xps/2005/06/resourcedictionary-key"
xml:lang="und" Width="816" Height="1056">
<Path Fill="#FFFFFFFF" Data="M0,0L816,0 816,1056 0,1056Z" />
<Canvas Clip="M0,0L816,0 816,1056 0,1056Z">
<Path Fill="#FFFFFFFF" Data="M0,0L816,0 816,1056 0,1056Z" />
<Path Fill="#FF008000" Data="M0,0L816,0 816,1056 0,1056Z" />
<Canvas RenderTransform="1,0,0,1,10,10">
<Path Fill="#FFFFFF00" Data="M0,0L796,0 796,120 0,120Z" />
<Canvas Clip="M0,0L796,0 796,120 0,120Z">
<Glyphs OriginX="0" OriginY="87.5866666666667" FontRenderingEmSize="96" FontUri="/Resources/1057478c-ad6c-46da-af29-3e00c349c111.ODTTF" UnicodeString="Rutger
Koperdraad" Fill="#FF000000" xml:lang="en-us" />
</Canvas>
</Canvas>
</Canvas>
</FixedPage>
I manage to get the rectangles and the vertical text position correctly printed to the XPS document writer using the code below:
Private Sub OnPrintPageEx(sender
As Object, e
As PrintPageEventArgs)
If m_intPageNumber < m_objPaginator.PageCount
Then
Using objGraphics
As System.Drawing.Graphics = e.Graphics
' Correction factor between WPF and printer units
Dim f As
Single = 100 / 96
' Set the graphics quality
objGraphics.SmoothingMode = Drawing.Drawing2D.SmoothingMode.None
objGraphics.InterpolationMode = Drawing.Drawing2D.InterpolationMode.NearestNeighbor
' Draw the green background
Dim stcRect1 As
New Drawing.RectangleF(0, 0, 816 * f, 1056 * f)
Call objGraphics.FillRectangle(Drawing.Brushes.DarkGreen, stcRect1)
' Draw the yellow rectangle
Dim stcRect2 As
New Drawing.RectangleF(0, 0, 796 * f, 120 * f)
Call objGraphics.TranslateTransform(10 * f, 10 * f)
Call objGraphics.FillRectangle(Drawing.Brushes.Yellow, stcRect2)
' Draw the text
Dim objFont As
New Drawing.Font("Times New Roman", 72)
Dim intEmHeight As
Integer = objFont.FontFamily.GetEmHeight(objFont.Style)
Dim intCellAscent
As Integer = objFont.FontFamily.GetCellAscent(objFont.Style)
Dim sngOffset As
Single = 87.58667F - 96.0F / intEmHeight * intCellAscent
Dim stcRect3 As
New Drawing.RectangleF(0, sngOffset * f, 796 * f, 120 * f)
Call stcRect3.Inflate(100 / 96, 100 / 96)
Call objGraphics.DrawString("Rutger Koperdraad", objFont, Drawing.Brushes.Black, stcRect3)
End Using
m_intPageNumber += 1
e.HasMorePages = (m_intPageNumber < m_objPaginator.PageCount)
End If
End Sub
However, the horizontal text positioning is still different. The first letter starts too far to the right and the overall text is wider. How can I reproduce the XAML correctly in the GDI+?
To give some background: I have a WPF application that can print using WPF/XPS technology. Since this print path gives quality problems on many legacy printer driver (bad image resolution due to a bug in the XPS to GDI+ conversion), I am building an
alternative print engine based on the GDI+. So effectively, I need to convert my WPF graphics to the GDI+.
Rutger Koperdraad.OK, I found the answer myself. By adding the string format as below, I get the correct result.
' Draw the text
Dim objFont As
New Drawing.Font("Times New Roman", 72)
Dim intEmHeight As
Integer = objFont.FontFamily.GetEmHeight(objFont.Style)
Dim intCellAscent
As Integer = objFont.FontFamily.GetCellAscent(objFont.Style)
Dim sngOffset As
Single = 87.58667F - 96.0F / intEmHeight * intCellAscent
Dim stcRect3 As
New Drawing.RectangleF(0, sngOffset * f, 796 * f, 120 * f)
Dim objFormat As
New Drawing.StringFormat(Drawing.StringFormat.GenericTypographic)
Call objGraphics.DrawString("Rutger Koperdraad", objFont, Drawing.Brushes.Black, stcRect3, objFormat)
Rutger Koperdraad.
Thank you for sharing your solutions and experience here. It will be very beneficial for other community members who have similar questions.
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
How to anchor zoom point in ScrollViewer+Image?
I'm using the following XAML to allow the user to pan and zoom with an image:
<ScrollViewer x:Name="scrollViewer" HorizontalSnapPointsType="None" HorizontalScrollBarVisibility="Auto" VerticalSnapPointsType="None" ZoomSnapPointsType="None" IsHorizontalRailEnabled="False" IsVerticalRailEnabled="False" ManipulationMode="All" VerticalScrollBarVisibility="Auto" ManipulationDelta="ScrollViewer_ManipulationDelta_1" IsDoubleTapEnabled="False" IsRightTapEnabled="False" IsTapEnabled="False">
<Image x:Name="pannableImage" Source="{Binding FullSizedImage}" ManipulationMode="All" Loaded="pannableImage_Loaded" IsDoubleTapEnabled="False" IsHitTestVisible="False" IsHoldingEnabled="False" IsRightTapEnabled="False" IsTapEnabled="False" ScrollViewer.VerticalScrollBarVisibility="Disabled" LayoutUpdated="pannableImage_LayoutUpdated">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="Scale" />
<RotateTransform x:Name="Rotate" />
<TranslateTransform x:Name="Translate" />
</TransformGroup>
</Image.RenderTransform>
</Image>
</ScrollViewer>
What I want to be able to do is keep the starting point of the zoom in the same place on the screen as the user zooms in or out.
In order to do that, I need to know the coordinates in the image where the zoom is starting so that I can then:
Get the screen coordinates for the image coordinates before the new scale factor is applied.
Get the screen coordinates for the image coordinates after the new scale factor is applied.
Adjust the translate transform so that the position stays the same
My problem lies in getting the point that the user is starting the zoom and then translating that into the underlying coordinates in the image.
I've tried:
private void scrollViewer_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
Debug.WriteLine("scrollViewer_ManipulationStarted: position = {0},{1}", e.Position.X, e.Position.Y);
GeneralTransform gt = pannableImage.TransformToVisual(scrollViewer);
GeneralTransform gti = gt.Inverse;
Point pt = gti.TransformPoint(e.Position);
Debug.WriteLine("scrollViewer_ManipulationStarted: image pos = {0},{1}", pt.X, pt.Y);
but the "image pos" numbers aren't right. It doesn't seem to matter if I pass scrollViewer or null to TransformToVisual.
This is for a Windows Universal App so needs to work on both Windows 8.1 and Windows Phone 8.1.
Can someone please advise a solution?
Thanks.Hi Herro
Thank you for suggesting that code sample. It certainly does support zooming in and out beneath the manipulation point.
However, I am struggling to modify my existing implementation to support that different approach. There are a few areas where I'm having trouble and it may be that I just don't fully understand how the transforms work.
When the image is loaded, I want to make sure that, initially at least, the image is scaled so that it fits onto the screen. I'm using various events to trigger that initialisation but the core of the code is this:
double visibleHeight = Window.Current.Bounds.Height; // scrollViewer.ViewportHeight; //
double visibleWidth = Window.Current.Bounds.Width; // scrollViewer.ViewportWidth; //
// Get the image dimensions, allowing for rotation. We can be certain about
// using the values of 0, 90, 180, 270 because the rotation is always done in
// multiples of 90.
double imageHeight, imageWidth;
if (Math.Abs(selectedObject.Rotation) == 180 || selectedObject.Rotation == 0)
imageHeight = ManipulateMe.ActualHeight;
imageWidth = ManipulateMe.ActualWidth;
else
imageWidth = ManipulateMe.ActualHeight;
imageHeight = ManipulateMe.ActualWidth;
// If the image is larger than a screen dimension, work out
// what factor we want to make that dimension fit.
double scaleX, scaleY;
if (imageWidth > visibleWidth)
scaleX = visibleWidth / imageWidth;
else
scaleX = 1.0;
if (imageHeight > visibleHeight)
scaleY = visibleHeight / imageHeight;
else
scaleY = 1.0;
// Pick the SMALLER of the scale factors so that we ensure both
// dimensions fit onto the screen. Smaller because the values
// should be less than 1, so the smaller the value, the more the
// image is going to be reduced in size.
double scale;
if (scaleX < scaleY)
scale = scaleX;
else
scale = scaleY;
// Don't allow scale to be MORE than 1, at least initially. User can zoom in later.
if (scale > 1.0)
scale = 1.0;
if (scale != 1.0)
_compositeTransform.TranslateX = 0.0;
double scaledHeight = imageHeight * scaleY;
_compositeTransform.TranslateY = -(visibleHeight - scaledHeight) / 2;
_compositeTransform.CenterX = ManipulateMe.ActualWidth / 2;
_compositeTransform.CenterY = ManipulateMe.ActualHeight / 2;
_compositeTransform.ScaleX = _compositeTransform.ScaleY = scale;
Rect imageRect = _compositeTransform.TransformBounds(new Rect(0.0, 0.0, ManipulateMe.ActualWidth, ManipulateMe.ActualHeight));
double visibleLeft = 0, visibleTop = 0;
// Need to ensure that the image is positioned top-left
if (imageRect.Left != visibleLeft)
_compositeTransform.TranslateX = visibleLeft - imageRect.Left;
if (imageRect.Top != visibleTop)
_compositeTransform.TranslateY = visibleTop - imageRect.Top;
Now, when the page loads and displays the image, the image is perfect - scaled and positioned just right. However, if I then try to move the image, it vanishes and debugging information shows that the coordinates of the image are all over the place.
I *suspect* that the problem is being caused by my code setting up these initial values. My problem is that I don't know when to reset them or to what values.
My next problem is to do with the panning. I want to ensure that the user doesn't lose the image, so I want to ensure that when the image is larger than the screen, the right hand edge of the image can be off to the right but cannot move more to the left
than the right hand edge of the screen. Similarly for the other three sides of the image. My code works but it causes "bounces" in that the image seems to move back away from the screen edge and then back again to where I had "locked"
the edge. Again, it may be because I need to reset a translation value but I just don't know when or what to.
Below is my modified version of the ManipulationDelta routine:
void ManipulateMe_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
if (forceManipulationsToEnd)
e.Complete();
return;
_previousTransform.Matrix = _transformGroup.Value;
Point center = _previousTransform.TransformPoint(new Point(e.Position.X, e.Position.Y));
_compositeTransform.CenterX = center.X;
_compositeTransform.CenterY = center.Y;
// Reset rotation when user moves image around
_compositeTransform.Rotation = 0;
_compositeTransform.ScaleX = _compositeTransform.ScaleY = e.Delta.Scale;
Rect imageRect = ManipulateMe.RenderTransform.TransformBounds(new Rect(0.0, 0.0, ManipulateMe.ActualWidth, ManipulateMe.ActualHeight));
Debug.WriteLine("LTRB: {0},{1},{2},{3}", imageRect.Left, imageRect.Top, imageRect.Right, imageRect.Bottom);
double visibleHeight = Window.Current.Bounds.Height; // scrollViewer.ViewportHeight; //
double visibleWidth = Window.Current.Bounds.Width; // scrollViewer.ViewportWidth; //
double visibleLeft = 0, visibleRight = visibleWidth, visibleTop = 0, visibleBottom = visibleHeight;
double xAdjustment = e.Delta.Translation.X;
double yAdjustment = e.Delta.Translation.Y;
// If the image is SMALLER than the screen, don't let the edges of the image go beyond the screen edges
// If the image is LARGER than the screen, make sure that the edges of the image are either all outside
// the screen edges or stuck to the screen edges.
if (imageRect.Width <= visibleWidth)
Debug.WriteLine("... image is narrower than the screen");
// Lock to the left hand side
if ((imageRect.Left + xAdjustment) != visibleLeft)
xAdjustment -= (imageRect.Left + xAdjustment - visibleLeft);
else
//Debug.WriteLine("... image is wider than the screen");
if ((imageRect.Right + xAdjustment) < visibleRight)
Debug.WriteLine("... stopping image from moving off the right edge");
Debug.WriteLine("... right before adjustment = {0}", imageRect.Right);
Debug.WriteLine("... adjustment is {0}", xAdjustment);
Debug.WriteLine("... so potential new right is {0}", imageRect.Right + xAdjustment);
xAdjustment = (visibleRight - imageRect.Right);
Debug.WriteLine("... new adjustment is {0}", xAdjustment);
Debug.WriteLine("... and new right is {0}", imageRect.Right + xAdjustment);
if ((imageRect.Left + xAdjustment) > visibleLeft)
Debug.WriteLine("... stopping image from moving off the left edge");
Debug.WriteLine("... left before adjustment = {0}", imageRect.Left);
Debug.WriteLine("... adjustment is {0}", xAdjustment);
Debug.WriteLine("... so potential new left is {0}", imageRect.Left + xAdjustment);
xAdjustment = (visibleLeft - imageRect.Left);
Debug.WriteLine("... new adjustment is {0}", xAdjustment);
Debug.WriteLine("... and new left is {0}", imageRect.Left + xAdjustment);
if (imageRect.Height <= visibleHeight)
Debug.WriteLine("... image is shorter than the screen");
// Lock to the top
if ((imageRect.Top + yAdjustment) != visibleTop)
yAdjustment -= (imageRect.Top + yAdjustment - visibleTop);
else
//Debug.WriteLine("... image is taller than the screen");
if ((imageRect.Bottom + yAdjustment) < visibleBottom)
Debug.WriteLine("... stopping image from moving off the bottom edge");
Debug.WriteLine("... bottom before adjustment = {0}", imageRect.Bottom);
Debug.WriteLine("... adjustment is {0}", yAdjustment);
Debug.WriteLine("... so potential new bottom is {0}", imageRect.Bottom + yAdjustment);
yAdjustment = (visibleBottom - imageRect.Bottom);
Debug.WriteLine("... new adjustment is {0}", yAdjustment);
Debug.WriteLine("... and new bottom is {0}", imageRect.Bottom + yAdjustment);
if ((imageRect.Top + yAdjustment) > visibleTop)
Debug.WriteLine("... stopping image from moving off the top edge");
Debug.WriteLine("... top before adjustment = {0}", imageRect.Top);
Debug.WriteLine("... adjustment is {0}", yAdjustment);
Debug.WriteLine("... so potential new top is {0}", imageRect.Top + yAdjustment);
yAdjustment = (visibleTop - imageRect.Top);
Debug.WriteLine("... new adjustment is {0}", yAdjustment);
Debug.WriteLine("... and new top is {0}", imageRect.Top + yAdjustment);
_compositeTransform.TranslateX = xAdjustment;
_compositeTransform.TranslateY = yAdjustment;
e.Handled = true;
Many thanks for any suggestions you can make.
Regards
Philip -
Image Splicing Effect Challenge (Part 1)
I ran across a neat image effect on this image:
Rock In Rio
Thought it might be neat to see how different people in the forums would go about doing this...
Anyhow. Looking forward to your ideas. Take care.
UPDATE*
This thread has been continued into the following thread:
Image Splicing Effect Challenge (Part 2)
“If you want something you've never had, you need to do something you've never done.”
Don't forget to mark
helpful posts and answers
! Answer an interesting question? Write a
new article
about it! My Articles
*This post does not reflect the opinion of Microsoft, or its employees.I am early staking my claim to pathclip.
Imports System.Drawing.Drawing2D
Public Class Form3
Private path1 As New Drawing2D.GraphicsPath
Private BorderColor As Color = Color.Goldenrod
Private MouseDownIndex As Integer = -1
Private MouseDownX, MouseDownY, MouseDownBmpX, MouseDownBmpY As Integer
Private OffsetX, OffsetY, SliceWidth, SliceStep As Integer
Private bmpSlice As Bitmap = New Bitmap("C:\bitmaps\metallica\metallica bw.jpg")
Private bmpBack As Bitmap = New Bitmap("C:\bitmaps\metallica\metallica background logo.png")
Structure bmpPoint
Public x As Integer
Public y As Integer
Public bmp As Bitmap
End Structure
Private bmpPointList As New List(Of bmpPoint)
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitilizeControls()
Form5_Resize(0, Nothing)
End Sub
Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
With e.Graphics
'draw background fit to window
Using bmpScene As Bitmap = New Bitmap(PictureBox1.ClientSize.Width, PictureBox1.ClientSize.Height)
Using g As Graphics = Graphics.FromImage(bmpScene)
'make temp image, fit to window
g.DrawImage(bmpBack, 0, 0, bmpScene.Width, bmpScene.Height)
'copy temp image to background
If CheckBox2.Checked Then
'add fuzzy
Dim t As Integer = NumericUpDown7.Value + 1
If t > 1 Then
For y = 0 To bmpScene.Height - 1
For x = 0 To bmpScene.Width - 1
If x Mod t = 0 And y Mod t = 0 Then
bmpScene.SetPixel(x, y, Color.White)
End If
Next
Next
End If
.DrawImage(bmpScene, 0, 0)
End If
End Using
End Using
'draw each slice path with inner bitmap
'set translate for global scene
.SmoothingMode = SmoothingMode.AntiAlias
.TranslateTransform(OffsetX - SliceWidth, OffsetY - SliceStep)
For i = 0 To bmpPointList.Count - 1
Using tbmp As Bitmap = bmpPointList(i).bmp.Clone
'setup coordinate origin for this slice
.TranslateTransform(SliceWidth, SliceStep)
'fade slice border edge
If NumericUpDown8.Value > 0 Then
Dim fadewidth As Integer = NumericUpDown8.Value * 10
'calc local coordinate of upper left slice on inner movable bitmap
Dim x2 As Single = path1.PathPoints(3).X - bmpPointList(i).x
Dim y2 As Single = path1.PathPoints(3).Y - bmpPointList(i).y
'calc angle of slice
Dim dx As Single = path1.PathPoints(0).X - path1.PathPoints(3).X
Dim dy As Single = path1.PathPoints(0).Y - path1.PathPoints(3).Y
Dim x1, y1, x3 As Integer
Dim oldClr, newClr As Color
'add fade to temp inner bitmap along edges of path
For y1 = y2 To y2 + dy
x2 += dx / dy
For z = 0 To fadewidth
x1 = Math.Floor(x2) + z
If x1 > 0 And x1 < tbmp.Width And y1 > 0 And y1 < tbmp.Height Then
'left side
oldClr = tbmp.GetPixel(x1, y1)
newClr = Color.FromArgb((255 \ fadewidth) * z, oldClr.R, oldClr.G, oldClr.B)
tbmp.SetPixel(x1, y1, newClr)
x3 = x1 + SliceWidth - (2 * z)
If x3 > 0 And x3 < tbmp.Width Then
'right side
oldClr = tbmp.GetPixel(x3, y1)
newClr = Color.FromArgb((255 \ fadewidth) * z, oldClr.R, oldClr.G, oldClr.B)
tbmp.SetPixel(x3, y1, newClr)
End If
End If
Next
Next
End If
'draw the image slice using the path clipping
.SetClip(path1)
.DrawImage(tbmp, bmpPointList(i).x, bmpPointList(i).y, tbmp.Width, tbmp.Height)
.ResetClip()
'draw border outline path
If CheckBox1.Checked Then .DrawPath(New Pen(BorderColor, 2), path1)
End Using
Next
If CheckBox2.Checked Then
.ResetTransform()
.DrawString("tommytwotrain", New Font("Rockwell Extra Bold", 12), New SolidBrush(BorderColor), 0, PictureBox1.Height - 30)
End If
End With
End Sub
Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown
'determine which slice was clicked
Using path2 As Drawing2D.GraphicsPath = path1.Clone
Dim Matrix1, matrix2 As New Matrix
MouseDownIndex = -1
Matrix1.Translate(OffsetX - SliceWidth, OffsetY - SliceStep)
path2.Transform(Matrix1)
matrix2.Translate(SliceWidth, SliceStep)
For i = 0 To bmpPointList.Count - 1
path2.Transform(matrix2)
If path2.IsVisible(e.X, e.Y) Then
MouseDownIndex = i
MouseDownX = e.X
MouseDownY = e.Y
MouseDownBmpX = bmpPointList(MouseDownIndex).x
MouseDownBmpY = bmpPointList(MouseDownIndex).y
Exit Sub
End If
Next
End Using
End Sub
Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove
If MouseDownIndex >= 0 Then
'move the image if dragging
Dim thisbmptom As New bmpPoint
thisbmptom = bmpPointList(MouseDownIndex)
thisbmptom.x = MouseDownBmpX - (MouseDownX - e.X)
thisbmptom.y = MouseDownBmpY - (MouseDownY - e.Y)
bmpPointList(MouseDownIndex) = thisbmptom
thisbmptom = Nothing
PictureBox1.Invalidate()
End If
End Sub
Private Sub PictureBox1_MouseUp(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseUp
MouseDownIndex = -1
End Sub
Private Sub Form5_Resize(sender As Object, e As EventArgs) Handles MyBase.Resize
Dim t As Integer = Me.ClientSize.Height - Panel1.Height
If t > 100 Then PictureBox1.Height = t Else PictureBox1.Height = 100
OffsetX = NumericUpDown3.Value * 10
OffsetY = NumericUpDown4.Value * 10
SliceWidth = NumericUpDown6.Value * 10
SliceStep = NumericUpDown5.Value * 5
'create the slice outline path geometry
Dim w1 As Single = PictureBox1.ClientSize.Width
Dim h1 As Single = 0.7 * PictureBox1.ClientSize.Height
Dim x1 As Single = 0.1 * w1
Dim a As Single = NumericUpDown2.Value * 10 / 57.3
Dim x As Single = Math.Cos(a) * h1 / Math.Sin(a)
Dim thePolygon() As PointF = {New PointF(x1, h1), _
New PointF(x1 + SliceWidth, h1), _
New PointF(x1 + SliceWidth + x, 0), _
New PointF(x1 + x, 0), _
New PointF(x1, h1)}
path1.Reset()
path1.AddLines(thePolygon)
PictureBox1.Invalidate()
End Sub
Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged
'create images for number of slices
bmpPointList.Clear()
Dim thisbmpTom As New bmpPoint
For i = 0 To NumericUpDown1.Value - 1
thisbmpTom.bmp = bmpSlice
bmpPointList.Add(thisbmpTom)
Next
Form5_Resize(0, Nothing)
PictureBox1.Invalidate()
End Sub
Private Sub NumericUpDowns_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown2.ValueChanged, NumericUpDown3.ValueChanged, NumericUpDown4.ValueChanged, NumericUpDown5.ValueChanged, NumericUpDown6.ValueChanged, NumericUpDown7.ValueChanged, NumericUpDown8.ValueChanged
'general settings
Form5_Resize(0, Nothing)
PictureBox1.Invalidate()
End Sub
Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles PictureBox2.Click
Dim cd As New ColorDialog
If cd.ShowDialog Then
BorderColor = cd.Color
PictureBox2.BackColor = BorderColor
End If
PictureBox1.Invalidate()
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged
'border, background
PictureBox1.Invalidate()
End Sub
Private Sub InitilizeControls()
PictureBox1.BackColor = Color.Black
PictureBox1.Dock = DockStyle.Bottom
PictureBox2.BackColor = BorderColor
Panel1.Dock = DockStyle.Top
CheckBox1.Checked = True
CheckBox2.Checked = True
NumericUpDown1.Value = 4 'slices
NumericUpDown1.Maximum = 7
NumericUpDown1.Minimum = 1
NumericUpDown2.Value = 6 'angle
NumericUpDown2.Maximum = 9
NumericUpDown2.Minimum = 1
NumericUpDown3.Value = -6 'offsetx
NumericUpDown3.Maximum = 30
NumericUpDown3.Minimum = -30
NumericUpDown4.Value = 3 'offsety
NumericUpDown4.Maximum = 30
NumericUpDown4.Minimum = -30
NumericUpDown5.Value = 2 'slice dy
NumericUpDown5.Maximum = 30
NumericUpDown5.Minimum = 0
NumericUpDown6.Value = 8 'slicewidth
NumericUpDown6.Maximum = 30
NumericUpDown6.Minimum = 1
NumericUpDown7.Value = 5 'fuzzy
NumericUpDown7.Maximum = 9
NumericUpDown7.Minimum = 0
NumericUpDown8.Maximum = 9 'fade
NumericUpDown8.Minimum = 0
NumericUpDown8.Value = 0
End Sub
End Class -
Add A label to a resizable an movable image
I have a project that does multi-touch...image moving, resizing etc. These images are loaded on the fly, so I don't know how many may load onto the canvas. The moving and resizing has all been worked out. However, I would like to put a label on each image.
When I place the Image usercontrol nto a container and make a label, I lose all ability to resize, which is crucial.
Here is the Picture controls XAML:
<UserControl x:Class="DocumentHandlingTouch.Picture"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image Source="{Binding Path=ImagePath}" Stretch="Fill" Width="Auto" Height="Auto" RenderTransformOrigin="0.5, 0.5">
<Image.RenderTransform>
<TransformGroup>
<RotateTransform Angle="{Binding Path=Angle}"></RotateTransform>
<ScaleTransform ScaleX="{Binding Path=ScaleX}" ScaleY="{Binding Path=ScaleY}"></ScaleTransform>
<TranslateTransform X="{Binding Path=X}" Y="{Binding Path=Y}"/>
</TransformGroup>
</Image.RenderTransform>
</Image>
</UserControl>
Here is some of the Picture controls class...the portion i use to set the image path:
public partial class Picture : UserControl
public Picture()
InitializeComponent();
DataContext = this;
public string ImagePath
get { return (string)GetValue(ImagePathProperty); }
set { SetValue(ImagePathProperty, value); }
public string ImageName
get { return (string)GetValue(ImageNameProperty); }
set { SetValue(ImageNameProperty, value); }
public static readonly DependencyProperty ImageNameProperty =
DependencyProperty.Register("ImageName", typeof(string), typeof(Picture), new UIPropertyMetadata(""));
the complete code for what I'm doing can be found on OneDrive at DocumentHandling.
Again, I am not looking for any help in getting these images to move or resize, what I'm looking for is a way to get a label onto these images that still allows them to be moved or resized.You could just add the following recursive FindParent method that will find the Picture parent element of the Image in the visual tree and make a small change to the FindPicture method in MainWindow.xaml.cs:
private Picture FindPicture(Point location)
HitTestResult result = VisualTreeHelper.HitTest(_canvas, location);
if (result == null)
return null;
Image image = result.VisualHit as Image;
if (image == null)
return null;
return FindParent<Picture>(image);
private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject {
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
..and use the following XAML markup for Picture.xaml user control:
<UserControl x:Class="DocumentHandlingTouch.Picture"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid.RenderTransform>
<TransformGroup>
<RotateTransform Angle="{Binding Path=Angle}"></RotateTransform>
<ScaleTransform ScaleX="{Binding Path=ScaleX}" ScaleY="{Binding Path=ScaleY}"></ScaleTransform>
<TranslateTransform X="{Binding Path=X}" Y="{Binding Path=Y}"/>
</TransformGroup>
</Grid.RenderTransform>
<Image Source="{Binding Path=ImagePath}" Stretch="Fill" Width="Auto" Height="Auto" RenderTransformOrigin="0.5, 0.5">
</Image>
<TextBlock Text="{Binding ImagePath}" VerticalAlignment="Bottom"/>
</Grid>
</UserControl>
Then it should work as expected.
Hope that helps.
Please remember to mark helpful posts as answer and please start a new thread if you have a new question. -
Cropping when moving and resizing a cropping rectangle
I created a program that crops an image and displays the cropped image but I'm trying to add more functionality
by making it movable and resizable. The rectangle moves and resizes but it only crops an image when user draws the rectangle and not when moved or resized. I know that the X,Y, height and width position of the rectangle would need to be updated but I'm not
sure how I can accomplish this being new to WPF. Below is my user control "CropControl and the code behind. Also, I'm implementing my code using MVVM framework.
XAML:
<UserControl x:Class="Klein_Tools_Profile_Pic_Generator.CropControl"
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:s="clr-namespace:Klein_Tools_Profile_Pic_Generator"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<ControlTemplate x:Key="MoveThumbTemplate" TargetType="{x:Type s:MoveThumb}">
<Rectangle Fill="Transparent"/>
</ControlTemplate>
<!-- ResizeDecorator Template -->
<ControlTemplate x:Key="ResizeDecoratorTemplate" TargetType="{x:Type Control}">
<Grid>
<s:ResizeThumb Width="3" Height="7" Cursor="SizeNS" Margin="0 -4 0 0"
VerticalAlignment="Top"/>
<s:ResizeThumb Width="3" Height="7" Cursor="SizeWE" Margin="-4 0 0 0"
VerticalAlignment="Stretch" HorizontalAlignment="Left"/>
<s:ResizeThumb Width="3" Height="7" Cursor="SizeWE" Margin="0 0 -4 0"
VerticalAlignment="Stretch" HorizontalAlignment="Right"/>
<s:ResizeThumb Width="3" Height="7" Cursor="SizeNS" Margin="0 0 0 -4"
VerticalAlignment="Bottom" HorizontalAlignment="Stretch"/>
<s:ResizeThumb Width="7" Height="7" Cursor="SizeNWSE"
VerticalAlignment="Top" HorizontalAlignment="Left"/>
<s:ResizeThumb Width="7" Height="7" Cursor="SizeNESW"
VerticalAlignment="Top" HorizontalAlignment="Right"/>
<s:ResizeThumb Width="7" Height="7" Cursor="SizeNESW"
VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
<s:ResizeThumb Width="7" Height="7" Cursor="SizeNWSE"
VerticalAlignment="Bottom" HorizontalAlignment="Right"/>
</Grid>
</ControlTemplate>
<!-- Designer Item Template-->
<ControlTemplate x:Key="DesignerItemTemplate" TargetType="ContentControl">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
<s:MoveThumb Template="{StaticResource MoveThumbTemplate}" Cursor="SizeAll"/>
<Control Template="{StaticResource ResizeDecoratorTemplate}"/>
<ContentPresenter Content="{TemplateBinding ContentControl.Content}"/>
</Grid>
</ControlTemplate>
</UserControl.Resources>
<Canvas x:Name="BackPanel"
MouseLeftButtonDown="LoadedImage_MouseLeftButtonDown"
MouseMove="LoadedImage_MouseMove"
MouseLeftButtonUp="LoadedImage_MouseLeftButtonUp"
Background="Transparent">
<ContentControl x:Name="contControl" Visibility="Collapsed"
Template="{StaticResource DesignerItemTemplate}">
<Rectangle x:Name="selectionRectangle" Fill="#220000FF"
IsHitTestVisible="False"/>
</ContentControl>
</Canvas>
</UserControl>
CODE BEHIND:
namespace Klein_Tools_Profile_Pic_Generator
/// <summary>
/// Interaction logic for CropControl.xaml
/// </summary>
public partial class CropControl : UserControl
private bool isDragging = false;
private Point anchorPoint = new Point();
private bool moveRect;
TranslateTransform trans = null;
Point originalMousePosition;
public CropControl()
InitializeComponent();
//Register the Dependency Property
public static readonly DependencyProperty SelectionProperty =
DependencyProperty.Register("Selection", typeof(Rect), typeof(CropControl), new PropertyMetadata(default(Rect)));
public Rect Selection
get { return (Rect)GetValue(SelectionProperty); }
set { SetValue(SelectionProperty, value); }
// this is used, to react on changes from ViewModel. If you assign a
// new Rect in your ViewModel you will have to redraw your Rect here
private static void OnSelectionChanged(System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e)
Rect newRect = (Rect)e.NewValue;
Rectangle selectionRectangle = d as Rectangle;
if (selectionRectangle != null)
return;
selectionRectangle.SetValue(Canvas.LeftProperty, newRect.X);
selectionRectangle.SetValue(Canvas.TopProperty, newRect.Y);
selectionRectangle.Width = newRect.Width;
selectionRectangle.Height = newRect.Height;
private void LoadedImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
if (isDragging == false)
anchorPoint.X = e.GetPosition(BackPanel).X;
anchorPoint.Y = e.GetPosition(BackPanel).Y;
Canvas.SetZIndex(selectionRectangle, 999);
isDragging = true;
BackPanel.Cursor = Cursors.Cross;
private void LoadedImage_MouseMove(object sender, MouseEventArgs e)
if (isDragging)
double x = e.GetPosition(BackPanel).X;
double y = e.GetPosition(BackPanel).Y;
contControl.SetValue(Canvas.LeftProperty, Math.Min(x, anchorPoint.X));
contControl.SetValue(Canvas.TopProperty, Math.Min(y, anchorPoint.Y));
contControl.Width = Math.Abs(x - anchorPoint.X);
contControl.Height = Math.Abs(y - anchorPoint.Y);
if (contControl.Visibility != Visibility.Visible)
contControl.Visibility = Visibility.Visible;
private void Image_MouseMove(object sender, MouseEventArgs e)
if (moveRect)
trans = selectionRectangle.RenderTransform as TranslateTransform;
if (trans == null)
selectionRectangle.RenderTransformOrigin = new Point(0, 0);
trans = new TranslateTransform();
selectionRectangle.RenderTransform = trans;
trans.Y = -(originalMousePosition.Y - e.GetPosition(BackPanel).Y);
trans.X = -(originalMousePosition.X - e.GetPosition(BackPanel).X);
e.Handled = false;
private void LoadedImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
if (isDragging)
isDragging = false;
if (contControl.Width > 0)
//Crop.IsEnabled = true;
//Cut.IsEnabled = true;
BackPanel.Cursor = Cursors.Arrow;
contControl.GetValue(Canvas.LeftProperty);
// Set the Selection to the new rect, when the mouse button has been released
Selection = new Rect(
(double)contControl.GetValue(Canvas.LeftProperty),
(double)contControl.GetValue(Canvas.TopProperty),
contControl.Width,
contControl.Height);Hello HotSawz,
The ResizeThumb and MoveThumb is not in your code so I cannot compile. Anyway, it is not the problem.
Anyway, can you clarify more details about "it only crops an image when user draws the rectangle and not when moved or resized", it is already normal behavoir for you to draw a rectangle and then move it. What kind of action do you want? Do you
mean some controls like this:
http://www.codeproject.com/Articles/23158/A-Photoshop-like-Cropping-Adorner-for-WPF
Best regards,
Barry
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Bitmap Rotation According to Mouse Position?
Hi,
I am working on a 2d computer graphics project, and I need a good function to rotate a Bitmap 360 degree according to my mouse position.
for example:Hi,
I am working on a 2d computer graphics project, and I need a good function to rotate a Bitmap 360 degree according to my mouse position.
for example:
Hello,
To rotate that image, we need to deal with the following tips.
1. The image size.
If the area for that image rotated is not big enough, it will just lose some parts of that image.
Here is a nice code shared in this thread
http://stackoverflow.com/questions/5199205/how-do-i-rotate-image-then-move-to-the-top-left-0-0-without-cutting-off-the-imag/5200280#5200280.
private Bitmap RotateImage(Bitmap b, float Angle)
// The original bitmap needs to be drawn onto a new bitmap which will probably be bigger
// because the corners of the original will move outside the original rectangle.
// An easy way (OK slightly 'brute force') is to calculate the new bounding box is to calculate the positions of the
// corners after rotation and get the difference between the maximum and minimum x and y coordinates.
float wOver2 = b.Width / 2.0f;
float hOver2 = b.Height / 2.0f;
float radians = -(float)(Angle / 180.0 * Math.PI);
// Get the coordinates of the corners, taking the origin to be the centre of the bitmap.
PointF[] corners = new PointF[]{
new PointF(-wOver2, -hOver2),
new PointF(+wOver2, -hOver2),
new PointF(+wOver2, +hOver2),
new PointF(-wOver2, +hOver2)
for (int i = 0; i < 4; i++)
PointF p = corners[i];
PointF newP = new PointF((float)(p.X * Math.Cos(radians) - p.Y * Math.Sin(radians)), (float)(p.X * Math.Sin(radians) + p.Y * Math.Cos(radians)));
corners[i] = newP;
// Find the min and max x and y coordinates.
float minX = corners[0].X;
float maxX = minX;
float minY = corners[0].Y;
float maxY = minY;
for (int i = 1; i < 4; i++)
PointF p = corners[i];
minX = Math.Min(minX, p.X);
maxX = Math.Max(maxX, p.X);
minY = Math.Min(minY, p.Y);
maxY = Math.Max(maxY, p.Y);
// Get the size of the new bitmap.
SizeF newSize = new SizeF(maxX - minX, maxY - minY);
// ...and create it.
Bitmap returnBitmap = new Bitmap((int)Math.Ceiling(newSize.Width), (int)Math.Ceiling(newSize.Height));
// Now draw the old bitmap on it.
using (Graphics g = Graphics.FromImage(returnBitmap))
g.TranslateTransform(newSize.Width / 2.0f, newSize.Height / 2.0f);
g.RotateTransform(Angle);
g.TranslateTransform(-b.Width / 2.0f, -b.Height / 2.0f);
g.DrawImage(b, 0, 0);
return returnBitmap;
2. The location of that control which displays that image.
If we use a picturebox, and set its sizemode to autosize like the following line, then if you just want to rotate that image to show, and you don't want to that affects the original image, then we need to keep its center point.
this.pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
We could add resize event handler after we set image for that picturebox.
Point pOrign;
Size sOrign;private void Form1_Load(object sender, EventArgs e)
this.pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
Image img = Image.FromFile(@"D:\Documents\New folder\New folder\TestImage.PNG");
this.pictureBox1.Image = img;
this.pictureBox1.InitialImage = img;
pOrign = new Point(this.pictureBox1.Left , this.pictureBox1.Top );
sOrign = new Size(this.pictureBox1.Width, this.pictureBox1.Height);
this.pictureBox1.BorderStyle = BorderStyle.FixedSingle;
this.pictureBox1.Resize += pictureBox1_Resize;
private void pictureBox1_Resize(object sender, EventArgs e)
this.pictureBox1.Left = this.pOrign.X + (this.sOrign.Width - this.pictureBox1.Width) / 2;
this.pictureBox1.Top = this.pOrign.Y + (this.sOrign.Height - this.pictureBox1.Height) / 2;
3. The angle between that center point and your mouse postion.
We could get that value inside the picturebox's container's mouse_move event.
Double angleNew ; private void pictureBoxContainer_MouseMove(object sender, MouseEventArgs e)
angleNew = Math.Atan2(this.pOrign.Y + this.sOrign.Height / 2 - e.Y, this.pOrign.X + this.sOrign.Width/2 - e.X) * 180.0 / Math.PI;
But when to start rotate that image, it should be your chooice, and you could decide when rotate that image with the following line.
this.pictureBox1.Image = (Image)RotateImage(new Bitmap(this.pictureBox1.InitialImage), (float)angleNew);
If you just want to save that change to that image, then you could save that bitmap to file directly.
Happy new year.
Regards.
Carl
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Simulation a car movement in wpf
please..
how can make a simulation of car rotation
in c# wpf codeYou could use an animation to change the values of the X and Y properties of a TranslateTransform that is applied to the "car" UI element to move it. If you want to begin another animation once the first one has finished you could just handle the
Completed event of the first animation.
Here is an example that moves an Ellipse element 250 dip to the right in a Canvas and then 300 dip down:
Ellipse car = new Ellipse();
car.Fill = Brushes.Black;
car.Width = 50;
car.Height = 50;
TranslateTransform tt = new TranslateTransform();
car.RenderTransform = tt;
DoubleAnimation anim1 = new DoubleAnimation(0, 250, TimeSpan.FromSeconds(3));
anim1.Completed += (s, e) =>
DoubleAnimation anim2 = new DoubleAnimation(0, 300, TimeSpan.FromSeconds(1));
tt.BeginAnimation(TranslateTransform.YProperty, anim2);
tt.BeginAnimation(TranslateTransform.XProperty, anim1);
Canvas canvas = new Canvas();
canvas.Width = 500;
canvas.Height = 500;
canvas.Background = Brushes.Yellow;
canvas.Children.Add(car);
//add Canvas to a StackPanel in the window
stackPanel.Children.Insert(0, canvas);
That should get you the idea. Please don't expect anyone to write an entire application or method for you though. That's not that the forums are for. But the above example should definitely
get you started.
Hope that helps.
Please remember to mark helpful posts as answer and/or helpful.
Maybe you are looking for
-
I purchased songs from Itunes store and I would like to record a CD to my parents with specific songs but when introduce the cd a message appears that the songs are not in MP3 format, how could I convert them?
-
Is it a good idea to upgrade my imac from 10.6.8 snow leopard to osx maverics?
I am thinking of upgrading, any problems with this come up? thanks for help!
-
The sales order item & contains a different material
Hi, Converted requisition into purchase order and now getting the following error: "The sales order item & contains a different material" Any advice?
-
Nano 5G says 0 songs after successfull synching
This is driving me insane. I bring my Nano home from the gym to update it and it first says that it needs to be reset so I wipe the lot. After rechoosing my audio books and albums it merrily goes away and syncs about 7Gb in total. It tells me the nan
-
Where to download Adobe Encore?
Hello, where can I download the latest Adobe Encore version? Since Adobe went live with Cloud 2014, I'm not able to find a dowload link to the old CS6 Version of Premiere which includes Encore CS6. Any ideas where I can find it? Is there another way