I have a image inside a canvas. When a UserControl loaded, image move up.
<Canvas x:Name="cnvMain" Width="300" VerticalAlignment="Center" Height="200" SnapsToDevicePixels="True">
<Image x:Name="Image1" Width="200" Stretch="None" Canvas.Bottom="0" Source="ImageGallery/Desert.jpg" ></Image>
</Canvas>
I used DoubleAnimation.
DoubleAnimation _Animation;
private Storyboard _StoryBoard;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
_Animation = new DoubleAnimation();
_Animation.From = -Image1.ActualHeight;
_Animation.To = cnvMain.ActualHeight;
_Animation.RepeatBehavior = RepeatBehavior.Forever;
_Animation.Duration = new Duration(TimeSpan.Parse("0:0:10"));
_Animation.FillBehavior = FillBehavior.Stop;
Storyboard.SetTarget(_Animation, Image1);
Storyboard.SetTargetProperty(_Animation, new PropertyPath(Canvas.BottomProperty));
_StoryBoard = new Storyboard();
_StoryBoard.Children.Add(_Animation);
_StoryBoard.Begin();
}
This code work well. My problem is the canvas did not overlay around of image like a frame (Image size is bigger of canvas and I want area of image inside canvas viewed). When I change Canvas to Grid it overlay outside of image but the animation did not work.
Try and use ClipToBounds="True" on your Canvas:
Related
I have a wpf application with two panes similar to powerpoint application:
left pane which shows list of all the panels in listbox
right pane which shows the selected panel
In the listbox I want to display panel as thumbnail and update the thumbnail as an when new controls are added to panel in right pane.
Just like powerpoint application thumbnail behaviour.
By using RenderTargetBitmap and PngBitmapEncoder we can capture a region of window.
and by using the PngBitmapEncoder frame Property assigned it to Image Source.
Lets start with Xaml
I divided the window by two half and left and right panel. Same in PowerPoint with less style. In order to demonstrate I have implemented to add TextBox on the right panel and the preview will be displayed on the left panel thumbnail.
<Grid Background="Aqua" x:Name="gridg">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox HorizontalAlignment="Left" Height="372" Margin="10,38,0,0" VerticalAlignment="Top" Width="306" Grid.Column="0" x:Name="Listtems" SelectionChanged="Listtems_SelectionChanged" />
<Button Content="+ TextBox" HorizontalAlignment="Left" Margin="142,10,0,0" VerticalAlignment="Top" Width="174" Click="Button_Click" Grid.Column="0"/>
<StackPanel x:Name="stackPanel" Background="Wheat" Grid.ColumnSpan="2" Margin="321,0,0,0" />
</Grid>
As soon as you click on the left panel item, the corresponding the control will be displayed on the right panel with the data.
In order to keep track of the items in the ListBox, I have used Dictionary with ItemIndex and to it's corresponding item's index used control.
Window's Code Behind
/// <summary>
/// Interaction logic for Window6.xaml
/// </summary>
public partial class Window6 : Window
{
Dictionary<int, Control> _dictionaryControls = new Dictionary<int, Control>();
DispatcherTimer dispatcherTimer = new DispatcherTimer();
public Window6()
{
InitializeComponent();
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Start();
}
private void BmpImage()
{
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap(800, 450, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(stackPanel);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
Image img = new Image();
img.Source = pngImage.Frames[0];
img.Height = 148;
img.Width = 222;
Listtems.Items.Add(img);
Listtems.SelectedIndex = Listtems.Items.Count - 1;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
stackPanel.Children.Clear();
int item = Listtems.Items.Count;
TextBox txtControl = new TextBox();
txtControl.FontSize = 100;
txtControl.Height = 122;
txtControl.TextWrapping = TextWrapping.Wrap;
_dictionaryControls.Add(item, txtControl);
stackPanel.Children.Add(txtControl);
stackPanel.UpdateLayout();
BmpImage();
}
private void Listtems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateThumbNail();
}
private void UpdateThumbNail()
{
int indexbackup = -1;
Listtems.SelectionChanged -= Listtems_SelectionChanged;
Control control;
_dictionaryControls.TryGetValue(Listtems.SelectedIndex, out control);
if (control == null)
{
Listtems.SelectionChanged += Listtems_SelectionChanged;
return;
}
indexbackup = Listtems.SelectedIndex;
stackPanel.Children.Clear();
stackPanel.Children.Add(control);
stackPanel.UpdateLayout();
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap(800, 450, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(stackPanel);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
Image img = new Image();
img.Source = pngImage.Frames[0];
img.Height = 148;
img.Width = 222;
Listtems.Items.Insert(Listtems.SelectedIndex, img);
Listtems.Items.RemoveAt(Listtems.SelectedIndex);
Listtems.SelectedIndex = indexbackup;
Listtems.SelectionChanged += Listtems_SelectionChanged;
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
UpdateThumbNail();
}
}
BmpImage() : - I used to capture or in other words the print screen of the StackPanel control.
Button_Click Event :- Is used to create a new Item in ListBox adding Image with the current print screen of the TextBox Control in StackPanel. It also adds control in _dictionaryControls variable.
Listtems_SelectionChanged Event:- Clears the StackPanel and then take the TextBox Control from _dictionaryControls based on the SelectedIndex of ListBox and place it in the StackPanel by taking current snapshot of the StackPanel.
For Demo Purpose, I have done it only for TextBox Control, but you can do it for any other control with a little tweaking.
UpdateThumbNail created a method responsible to update the image in Listbox based on the ListBoxItem.
dispatcherTimer_Tick : - Event is responsible to call the UpdateThumbNail() Method for every second.
I use MediaElement and (Time)Slider to play and control playing of a video.
I used answer 2 to this question as a base.
In addition to the dragging capability I would also like the slider thumb to be moved to a mouse click point.
This works ok when the MediaElement and (Time)Slider are paused, but when the video is playing a mouse click has no effect
Here is my code
XAML:
<MediaElement Source="..."
Name="mediaView"
Height="450" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="UniformToFill"
MediaOpened="OnMediaOpened" MediaEnded="OnMediaEnded" MediaFailed="OnMediaFailed" Grid.Row="0" Grid.Column="0"/>
<Grid Name="mediaBar" VerticalAlignment="Bottom" Margin="5,10,5,0" Background="#B2282828" Grid.Row="0" Grid.Column="0">
<!-- ... -->
<Slider Name="timeSlider" Margin="5,5,5,0"
Thumb.DragStarted="OnDragStarted" Thumb.DragCompleted="OnDragCompleted" ValueChanged="OnTimeSliderValueChanged"
PreviewMouseLeftButtonUp="OnMouseLeftButtonUp" IsMoveToPointEnabled="True"
MinWidth="200" FlowDirection="LeftToRight"
Grid.Column="4" Cursor="ScrollWE" VerticalAlignment="Center"/>
<!-- ... -->
</Grid>
relevant c# part:
private void OnDragStarted(object sender, DragStartedEventArgs args)
{
isDragging = true;
ticks.Stop();
}
private void OnDragCompleted(object sender, DragCompletedEventArgs args)
{
isDragging = false;
int SliderValue = (int)timeSlider.Value;
TimeSpan ts = new TimeSpan(0, 0, 0, 0, SliderValue);
mediaView.Position = ts;
if(currentStatus == Status.PLAYING)
ticks.Start();
}
private void OnMouseLeftButtonUp(object sender, EventArgs ea)
{
if(!isDragging)
{
mediaView.Pause();
ticks.Stop();
int SliderValue = (int)timeSlider.Value; // when video is playing this not the point of the mouse click
// ...
}
}
I can understand that timeSlider.Value delivers the current point in time instead of the mouse click position when the video is playing.
Is there another way to measure the position of the mouse click and update the slider value with that ?
Or a better solution for the Mouse-click-while-slider-is-running-situation ?
Try this:
private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs ea)
{
mediaView.Position = TimeSpan.FromSeconds((int)(mediaView.NaturalDuration.TimeSpan.TotalSeconds * (double)(ea.GetPosition(timeSlider).X / this.Width)));
}
I'm doing a graphic editor for a GBA game and I got an image into a ScrollView. When the user click on a NumericUpDown, the image is resized with a magnify factor. I would like my ScrollView to adapt itself to the new size of the image to be able to scroll the entire image. I'm not using the MVVM patter.
Here is portion of my XAML:
<ScrollViewer x:Name="PortraitScrollBar" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" VerticalAlignment="Bottom" HorizontalAlignment="Right">
<Image x:Name="ImagePortrait" Width="280" Height="280" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top" />
</ScrollViewer>
Here also is my function that is called on the ValueChanged event of the NumericUpDown:
public static void Magnify(ref Image img, WriteableBitmap wBmp, int factor)
{
img.Source = wBmp.Resize(wBmp.PixelWidth * factor, wBmp.PixelHeight * factor, WriteableBitmapExtensions.Interpolation.NearestNeighbor);
}
private void PorMagnifyUpDown_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (IsInit)
{
Magnify(ref ImagePortrait, currentImage, (int)e.NewValue);
}
}
I have this DataGrid and this Canvas:
<DataGrid Canvas.ZIndex="1" x:Name="dgTimeline"/>
<Canvas Height="30" Width="999" Canvas.ZIndex="2" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="71,387,0,0">
<Line Name="time" X1="0" Y1="0" X2="0" Y2="24" Stroke="Black" StrokeThickness="2"/>
</Canvas>
Which results in:
However, when I move the horizontal scroll bar of the DataGrid the Canvas obviously stays on its position because its parent is the Window and not the DataGrid:
Is it possible to keep Canvas' position relative to the DataGrid instead of its parent in such a way that when scrolling the DataGrid the Canvas would stay stationary as it was a DataGrid's element? I tried to put the Canvas inside of the DataGrid but that didn't work.
You can add horizontal scrollbar to canvas and then try to synchronize the horizontal scrolls of canvas and datagrid. something like ...
private void dataGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
canvasScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
}
private void canvasScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
ScrollViewer dgScrollViewer = GetScrollViewerInstance();
dgScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
}
private ScrollViewer GetScrollViewerInstance()
{
var ctrl = VisualTreeHelper.GetChild(dataGrid, 0);
if (ctrl is Border)
{
var ctrl1 = VisualTreeHelper.GetChild(ctrl, 0);
if (ctrl1 is ScrollViewer)
{
dgScrollViewer = ctrl1 as ScrollViewer;
}
}
}
This code is just to give you an idea of how to do it and not a actual working code. You set the HorizontalScrollBarVisibility for Canvas to Hidden if you don't want to show it. You will not need the second event handler in that case.
As the title suggests, using WPF I want to have a scenario where I have a bitmap image with another bitmap overlayed on top of it and, using the mouse, "paint" over the top bitmap so that it reveals the bitmap underneath. Is this just as simple as painting with a transparent brush? I have tried this to no avail but maybe I am missing something.
You can use a VisualBrush to create an OpacityMask. Here is a code example of a dark green rectangle being replaced by a light green one. Using this approach the two rectangles could be any elements including images.
<Grid MouseMove="Grid_MouseMove">
<Rectangle Fill="DarkGreen"/>
<Rectangle Fill="LightGreen">
<Rectangle.OpacityMask>
<VisualBrush Stretch="None" AlignmentX="Left" AlignmentY="Top">
<VisualBrush.Visual>
<Path Name="path" Stroke="Black" StrokeThickness="10"/>
</VisualBrush.Visual>
</VisualBrush>
</Rectangle.OpacityMask>
</Rectangle>
</Grid>
and here is the code-behind:
private void Grid_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var point = e.GetPosition(sender as Grid);
if (lastPoint != nullPoint)
AddSegment(lastPoint, point);
lastPoint = point;
}
else
{
lastPoint = nullPoint;
}
}
private void AddSegment(Point point1, Point point2)
{
if (segments.Count == 0 || segments[segments.Count - 1].Point != point1)
segments.Add(new LineSegment(point1, false));
segments.Add(new LineSegment(point2, true));
var figures = new PathFigureCollection();
figures.Add(new PathFigure(new Point(), segments, false));
var geometry = new PathGeometry();
geometry.Figures = figures;
path.Data = geometry;
}
List<LineSegment> segments = new List<LineSegment>();
private static readonly Point nullPoint = new Point(-1, -1);
Point lastPoint = nullPoint;