How to remove video black bands in videoView with LibVlcSharp? - c#

when I play a video with video, it presents black bands in the top and bottom part of the video, like in image in the URL
https://imgur.com/a/JiUv8rt. I'd like to remove the bands and display just the video in an absolute layout. how can I reach my goal?
<pages:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
xmlns:shared="clr-namespace:LibVLCSharp.Forms.Shared;assembly=LibVLCSharp.Forms"
x:Class="App.Pages.WebcamVideoPopUpPage"
BackgroundColor="Transparent">
<pages:PopupPage.Animation>
<animations:ScaleAnimation
PositionIn="Center"
PositionOut="Center"
ScaleIn="1.2"
ScaleOut="0.8"
DurationIn="400"
DurationOut="300"
EasingIn="SinOut"
EasingOut="SinIn"
HasBackgroundAnimation="True"/>
</pages:PopupPage.Animation>
<AbsoluteLayout x:Name="AbsoluteLayoutWebcam"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<shared:VideoView x:Name="VideoViewWebcam"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="0, 0, 1, 1"
MediaPlayer ="{Binding MediaPlayer}"
MediaPlayerChanged ="VideoView_MediaPlayerChanged"/>
<Label x:Name="DescriptionWebcam"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="0, 0, 1, .2"
HorizontalOptions="Fill"
VerticalOptions="Fill"
Text="{Binding InfoWebcam}"
FontSize="Large"
TextColor="White"/>
</AbsoluteLayout>
</pages:PopupPage>
UPDATE
I update at latest pre-release as #mtz suggested me, and I modified my code in the following way:
public partial class WebcamVideoPopUpPage : PopupPage
{
public WebcamVideoPopUpPage()
{
var vm = App.Locator.WebCamVideoVM;
this.BindingContext = vm;
InitializeComponent();
MediaPlayerWebcam.VideoView.MediaPlayerChanged += VideoView_MediaPlayerChanged;
MediaPlayerWebcam.MediaPlayer.AspectRatio = "FitScreen";
}
protected override void OnAppearing()
{
base.OnAppearing();
Messenger.Default.Send(new OnApperingVideoMessage());
}
private void VideoView_MediaPlayerChanged(object sender, LibVLCSharp.Shared.MediaPlayerChangedEventArgs e)
{
Messenger.Default.Send(new OnVideoViewInitializedMessage());
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MediaPlayerWebcam.MediaPlayer.Stop();
MediaPlayerWebcam.MediaPlayer = null;
}
}
My xaml:
<AbsoluteLayout x:Name="AbsoluteLayoutWebcam"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<shared:MediaPlayerElement x:Name="MediaPlayerWebcam"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="0, 0, 1, .4"
MediaPlayer ="{Binding MediaPlayer}"/>
<Label x:Name="DescriptionWebcam"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="0, 0, 1, .2"
HorizontalOptions="Fill"
VerticalOptions="Fill"
Text="{Binding InfoWebcam}"
FontSize="Large"
TextColor="White"/>
</AbsoluteLayout>
My viewModel:
public class WebcamVideoViewModel : BaseViewModel
{
private LibVLC LibVLC { get; set; }
private bool IsLoaded { get; set; }
private bool IsVideoViewInitialized { get; set; }
private Media Media { get; set; }
private MediaPlayer _mediaPlayer;
public MediaPlayer MediaPlayer
{
get { return _mediaPlayer; }
set
{
_mediaPlayer = value;
OnPropertyChanged();
}
}
private string _InfoWebcam { get; set; }
public string InfoWebcam
{
get { return _InfoWebcam; }
set
{
_InfoWebcam = value;
OnPropertyChanged();
}
}
public WebcamVideoViewModel(INavigationService navigationService, IApiAutostradeManagerFactory apiAutostradeFactory) : base(navigationService, apiAutostradeFactory)
{
Messenger.Default.Register<InfoWebcamVideoMessage>(this, OnReceivedInfoWebcam);
Messenger.Default.Register<OnApperingVideoMessage>(this, OnAppearing);
Messenger.Default.Register<OnVideoViewInitializedMessage>(this, OnVideoViewInitialized);
Task.Run(Initialize);
}
private void Initialize()
{
Core.Initialize();
LibVLC = new LibVLC();
MediaPlayer = new MediaPlayer(LibVLC);
}
private async void OnReceivedInfoWebcam(InfoWebcamVideoMessage msg)
{
var response = await ApiManager.GetVideoWebcam(msg.Mpr, msg.Uuid);
if (response.IsSuccessStatusCode)
{
InfoWebcam = msg.T_Description_webcam;
var stream = await response.Content.ReadAsStreamAsync();
Media = new Media(LibVLC, stream);
Play();
}
}
public void OnAppearing(OnApperingVideoMessage msg)
{
IsLoaded = true;
}
public void OnVideoViewInitialized(OnVideoViewInitializedMessage msg)
{
IsVideoViewInitialized = true;
}
private void Play()
{
if (IsLoaded && IsVideoViewInitialized)
{
MediaPlayer.Play(Media);
}
}
}
Now i'm closer to solution because videoView is resizable with the button present at bootm, but I'd like to get at start the fill AspectRatio and I don't want anything expect the video(In other words, I'd want to remove seek bar and resize video button). Another problem is that after I close mediaPlayer, and I open again a new video, my app crashes. Any advice?

You need to change the aspect ratio to "fill the screen".
See how to here: https://github.com/videolan/libvlcsharp/blob/91b8f06ee1bedd9b3219a4e9ade0a9c44f59fda8/LibVLCSharp.Forms/Shared/PlaybackControls.xaml.cs#L926 or use the latest pre-release LibVLCSharp.Forms package that contains the MediaPlayerElement which has this feature built-in (soon in stable version).

What you just trying is to stretch the video. But remember it will effect video quality.
To remain simple, you can try this working and tested code:
MediaPlayerWebcam.MediaPlayer.AspectRatio = $"{MediaPlayerWebcam.Width.ToString()}:{MediaPlayerWebcam.Height.ToString()}";
MediaPlayerWebcam.Scale = 0;

My scenario is a fullscreen player, I do it with these codes refer to LibVLCSharp.Forms, hope it will be helpful. the code deal with fullscreen(commented) or fill screen with video.
public void PlayerFullScreen()
{
//restore
if (_isFullScreen)
{
RestoreDefaultWindowInfo();
_isFullScreen = false;
_mediaPlayer.Scale = _originalScale; //reset
_mediaPlayer.AspectRatio = _originalAspectRatio;
//Mouse.Capture(null);
playerBar.Visibility = Visibility.Visible;
}
else // fullscreen(stretch video)
{
this.WindowStyle = WindowStyle.None;
this.ResizeMode = ResizeMode.NoResize;
this.Left = 0;
this.Top = 0;
this.Width = SystemParameters.VirtualScreenWidth;
this.Height = SystemParameters.VirtualScreenHeight;
//this.Topmost = true;
_isFullScreen = true;
_originalScale = _mediaPlayer.Scale; // save original
_originalAspectRatio = _mediaPlayer.AspectRatio;
playerBar.Visibility = Visibility.Collapsed;
MediaTrack? mediaTrack;
try
{
mediaTrack = _mediaPlayer.Media?.Tracks?.FirstOrDefault(x => x.TrackType == TrackType.Video);
}
catch (Exception)
{
mediaTrack = null;
}
if (mediaTrack == null || !mediaTrack.HasValue)
{
return;
}
//get windows scale factor(DPI)
PresentationSource source = PresentationSource.FromVisual(this);
double dpiX=1.0, dpiY=1.0;
if (source != null)
{
dpiX = source.CompositionTarget.TransformToDevice.M11;
dpiY = source.CompositionTarget.TransformToDevice.M22;
}
var displayW = this.Width * dpiX;
var displayH = this.Height * dpiY;
var videoSwapped = mediaTrack.Value.Data.Video.Orientation == VideoOrientation.LeftBottom ||
mediaTrack.Value.Data.Video.Orientation == VideoOrientation.RightTop;
var videoW = mediaTrack.Value.Data.Video.Width;
var videoH = mediaTrack.Value.Data.Video.Height;
if (videoSwapped)
{
var swap = videoW;
videoW = videoH;
videoH = swap;
}
if (mediaTrack.Value.Data.Video.SarNum != mediaTrack.Value.Data.Video.SarDen)
videoW = videoW * mediaTrack.Value.Data.Video.SarNum / mediaTrack.Value.Data.Video.SarDen;
var ar = videoW / (float)videoH;
var dar = displayW / (float)displayH;
float scale;
if (dar >= ar)
scale = (float)displayW / videoW; /* horizontal */
else
scale = (float)displayH / videoH; /* vertical */
//keep ratio of width/height, not fill the srceen
//_mediaPlayer.Scale = scale; // 这是保持视频宽高比的,视频不会变形
//_mediaPlayer.AspectRatio = string.Empty;//这是保持视频宽高比的,视频不会变形
//这是视频变形适配屏幕的情况(满屏)
//fill all the screen by video,video is streched
float xscale, yscale;
xscale = (float)(displayW / videoW);
yscale = (float)(displayH / videoH);
_mediaPlayer.Scale = (xscale<yscale)? xscale:yscale;
string aspectRatio = String.Format("{0}:{1}",
this.Width,this.Height);
_mediaPlayer.AspectRatio = aspectRatio;
}
}

Related

Pinch-zoom an image but starting zoomed out

I'm writing Pinch/Zoom into my application, I have it working pretty good but am running into a problem or two. First, I want the image to start off, fully zoomed out. Where you see the whole image. Second, I want the application to stop zooming out when it reaches that point. So you can keep pinching/panning but it doesn't continue to calculate. Thanks in advance for you help. See below for the code.
public MainWindow()
{
InitializeComponent();
var files = System.IO.Directory.GetFiles(#"D:\", "*.jpg");
MainImage.Source = new BitmapImage(new Uri(files[0]));
}
private void Image_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
e.ManipulationContainer = ScrollViewerParent;
e.Handled = true;
}
private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
int nrOfPoints = 0;
lock (mutex)
{
nrOfPoints = nrOfTouchPoints;
}
if (nrOfPoints >= 2)
{
var matrix = MainImage.LayoutTransform.Value;
Point? centerOfPinch = (e.ManipulationContainer as FrameworkElement)?.TranslatePoint(e.ManipulationOrigin, ScrollViewerParent);
if (centerOfPinch == null)
{
return;
}
var deltaManipulation = e.DeltaManipulation;
matrix.ScaleAt(deltaManipulation.Scale.X, deltaManipulation.Scale.Y, centerOfPinch.Value.X, centerOfPinch.Value.Y);
MainImage.LayoutTransform = new MatrixTransform(matrix);
Point? originOfManipulation = (e.ManipulationContainer as FrameworkElement)?.TranslatePoint(e.ManipulationOrigin, MainImage);
double scrollViewerOffsetX = ScrollViewerParent.HorizontalOffset;
double scrollViewerOffsetY = ScrollViewerParent.VerticalOffset;
double pointMovedOnXOffset = originOfManipulation.Value.X - originOfManipulation.Value.X * deltaManipulation.Scale.X;
double pointMovedOnYOffset = originOfManipulation.Value.Y - originOfManipulation.Value.Y * deltaManipulation.Scale.Y;
double multiplicatorX = ScrollViewerParent.ExtentWidth / MainImage.ActualWidth;
double multiplicatorY = ScrollViewerParent.ExtentHeight / MainImage.ActualHeight;
ScrollViewerParent.ScrollToHorizontalOffset(scrollViewerOffsetX - pointMovedOnXOffset * multiplicatorX);
ScrollViewerParent.ScrollToVerticalOffset(scrollViewerOffsetY - pointMovedOnYOffset * multiplicatorY);
e.Handled = true;
}
else
{
ScrollViewerParent.ScrollToHorizontalOffset(ScrollViewerParent.HorizontalOffset - e.DeltaManipulation.Translation.X);
ScrollViewerParent.ScrollToVerticalOffset(ScrollViewerParent.VerticalOffset - e.DeltaManipulation.Translation.Y);
}
}
private void MainImage_TouchDown(object sender, TouchEventArgs e)
{
lock (mutex)
{
nrOfTouchPoints++;
}
}
private void MainImage_TouchUp(object sender, TouchEventArgs e)
{
lock (mutex)
{
nrOfTouchPoints--;
}
}
<ScrollViewer Grid.Row="1"
x:Name="ScrollViewerParent"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
PanningMode="Both">
<Image MouseDown="MainImage_MouseDown"
x:Name="MainImage"
IsManipulationEnabled="True"
TouchDown="MainImage_TouchDown"
TouchUp="MainImage_TouchUp"
ManipulationDelta="Image_ManipulationDelta"
ManipulationStarting="Image_ManipulationStarting"/>
</ScrollViewer>

How to create plots at runtime (OxyPlot)

I want to have a button which, when clicked, creates a new instance of a PlotView and adds it to a StackPanel. How can I do this?
I tried to come up with something but it doesn't work. Here is my code so far:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var plotView = new PlotView();
plotView.Height = 300;
plotView.Width = 600;
plotView.VerticalAlignment = System.Windows.VerticalAlignment.Top;
var oxyPlotModel = new OxyPlotModel();
var plotModel = new PlotModel();
plotView.DataContext = oxyPlotModel;
oxyPlotModel.PlotModel = plotModel;
SetUpAxes(ref plotModel);
plotModel.Axes[1].IsZoomEnabled = true;
stackPanel1.Children.Add(plotView);
}
private void SetUpAxes(ref PlotModel plotModel)
{
plotModel.Axes.Clear();
foreach (var axis in plotModel.Axes)
axis.Reset();
var yAxis = new OxyPlot.Axes.LinearAxis();
var xAxis = new OxyPlot.Axes.DateTimeAxis();
yAxis.IsZoomEnabled = false;
yAxis.AbsoluteMinimum = -50;
yAxis.AbsoluteMaximum = 450;
yAxis.MajorGridlineStyle = LineStyle.Solid;
xAxis.MajorGridlineStyle = LineStyle.Solid;
xAxis.AbsoluteMinimum = OxyPlot.Axes.DateTimeAxis.ToDouble(new DateTime(Convert.ToDateTime("21/01/14 " + "00:00:00").Ticks));
xAxis.AbsoluteMaximum = OxyPlot.Axes.DateTimeAxis.ToDouble(new DateTime(Convert.ToDateTime("21/01/14 " + "00:00:00").AddDays(1).Ticks));
yAxis.IsPanEnabled = false;
yAxis.IsZoomEnabled = false;
yAxis.Font = "Open Sans";
xAxis.Font = "Open Sans";
plotModel.Axes.Add(yAxis);
plotModel.Axes.Add(xAxis);
}
}
Here is my viewmodel:
public class OxyPlotModel : INotifyPropertyChanged
{
private OxyPlot.PlotModel plotModel;
public OxyPlot.PlotModel PlotModel
{
get
{
return plotModel;
}
set
{
plotModel = value;
OnPropertyChanged("PlotModel");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
Another option is to make the PlotViews invisible in the xaml itself and then reveal them one by one after a press of the button, but I feel like this method is better.
This sounds like a good job for a ListBox. In essence, just add your new chart to an iobservablecollection of charts.
xaml
<button command="{binding AddChart}" />
<ListBox ItemsSource="{Binding ChartDataSets}" IsSynchronizedWithCurrentItem="true">
<ListBox.ItemTemplate>
<DataTemplate>
<views:OxyPlotChart MinWidth="600" MinHeight="300" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
OxyPLotChart.xaml
<oxy:PlotView Model="{Binding}" />
in OxyPlotModel (*assuming your code is correct)
public IObservableCollection<PlotView> ChartDataSets;
public DelegateCommand AddChart { get; private set;}
public OxyPlotModel()
{
ChartDataSets = new ObservableCollection<PlotView>();
AddChart = new DelegateCommand(AddOxyChart);
}
private void AddOxyChart()
{
var plotView = new PlotView();
plotView.Height = 300;
plotView.Width = 600;
plotView.VerticalAlignment = System.Windows.VerticalAlignment.Top;
var oxyPlotModel = new OxyPlotModel();
var plotModel = new PlotModel();
plotView.DataContext = oxyPlotModel;
oxyPlotModel.PlotModel = plotModel;
SetUpAxes(ref plotModel);
plotModel.Axes[1].IsZoomEnabled = true;
ChartDataSets.Add(plotView);
}
private void SetUpAxes(ref PlotModel plotModel)
{
plotModel.Axes.Clear();
foreach (var axis in plotModel.Axes)
axis.Reset();
var yAxis = new OxyPlot.Axes.LinearAxis();
var xAxis = new OxyPlot.Axes.DateTimeAxis();
yAxis.IsZoomEnabled = false;
yAxis.AbsoluteMinimum = -50;
yAxis.AbsoluteMaximum = 450;
yAxis.MajorGridlineStyle = LineStyle.Solid;
xAxis.MajorGridlineStyle = LineStyle.Solid;
xAxis.AbsoluteMinimum = OxyPlot.Axes.DateTimeAxis.ToDouble(new DateTime (Convert.ToDateTime("21/01/14 " + "00:00:00").Ticks));
xAxis.AbsoluteMaximum = OxyPlot.Axes.DateTimeAxis.ToDouble(new DateTime(Convert.ToDateTime("21/01/14 " + "00:00:00").AddDays(1).Ticks));
yAxis.IsPanEnabled = false;
yAxis.IsZoomEnabled = false;
yAxis.Font = "Open Sans";
xAxis.Font = "Open Sans";
plotModel.Axes.Add(yAxis);
plotModel.Axes.Add(xAxis);
}

Xamarin.Forms Infinite Scrolling Image Background Effect

I'm trying to make what I think will be a nice effect for an app - a series of images (think wallpaper) will be constantly scrolling in the background during a view. I started prototyping this in Xamarin.Forms, creating a custom control. Planned on a diagonal translation but started with the most basic approach and still ran into some issues fairly quickly, namely that it is not entirely smooth as it gets a bit choppy here and there (even when using caching and just a 10kb image) and 2) if user executes an action that's more involved it may cause a lag and the images get rendered more closely together than they should be. Is there a way to fix up this approach so that it's as smooth as possible and doesn't interfere (or get interfered with) the other UI elements, or is there a far superior approach for something like this - anyone ever tackle this? Please let me know, thanks.
FlyingImageBackground.cs
public class FlyingImageBackground : ContentView
{
public static readonly BindableProperty FlyingImageProperty =
BindableProperty.Create(nameof(FlyingImage), typeof(ImageSource), typeof(FlyingImageBackground), default(ImageSource), BindingMode.TwoWay, propertyChanged: OnFlyingImageChanged);
public ImageSource FlyingImage
{
get => (ImageSource)GetValue(FlyingImageProperty);
set => SetValue(FlyingImageProperty, value);
}
private AbsoluteLayout canvas;
public FlyingImageBackground()
{
this.canvas = new AbsoluteLayout()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
this.canvas.SizeChanged += Canvas_SizeChanged;
Content = this.canvas;
}
~FlyingImageBackground() => this.canvas.SizeChanged -= Canvas_SizeChanged;
private static void OnFlyingImageChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (FlyingImageBackground)bindable;
control.BringToLife();
}
private void BringToLife()
{
if (this.canvas.Width <= 0 || this.canvas.Height <= 0)
return;
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
Device.BeginInvokeOnMainThread(async () =>
{
await SendImageWave();
});
return this.canvas.IsVisible;
});
}
private async Task SendImageWave()
{
var startingX = -100;
var endingX = this.canvas.Width;
if (endingX <= 0)
return;
endingX += 100;
var yPositions = Enumerable.Range(0, (int)this.canvas.Height).Where(x => x % 90 == 0).ToList();
var imgList = new List<CachedImage>();
foreach (var yPos in yPositions)
{
var img = new CachedImage
{
Source = FlyingImage,
HeightRequest = 50
};
imgList.Add(img);
this.canvas.Children.Add(img, new Point(startingX, yPos));
}
await Task.WhenAll(
imgList.Select(x => x.TranslateTo(endingX, 0, 10000)));
//.Concat(imgList.Select(x => x.TranslateTo(startingX, 0, uint.MinValue))));
imgList.ForEach(x =>
{
this.canvas.Children.Remove(x);
x = null;
});
imgList = null;
}
private void Canvas_SizeChanged(object sender, EventArgs e)
{
BringToLife();
}
}
Usage example:
Just put it into a Grid in a ContentPage along with the main content:
e.g.:
<ContentPage.Content>
<Grid>
<controls:FlyingImageBackground FlyingImage="fireTruck.png" />
<StackLayout HorizontalOptions="Center">
<Button
Text="I'm a button!" />
<Label
FontAttributes="Bold,Italic"
Text="You're a good man, old sport!!!"
TextDecorations="Underline" />
</StackLayout>
</Grid>
</ContentPage.Content>
Switched to SkiaSharp and much better results. The animation appears smooth and if the flow gets interrupted the images maintain their appropriate distance. Also realized in the first draft using the built-in Xamarin Animations that I screwed up the check for when to run it; .IsVisible prop will remain true even if the page isn't even on the screen anymore, so in this new version needed to bind to a property that tells me if the page is actually active or not (based on when it gets navigated to and navigated away from) and if not then stop the animation. This is still just handling the horizontal scrolling effect for now. Hope someone else finds it useful, and any other improvements would be welcome, please just comment/post an answer!
[DesignTimeVisible(true)]
public class FlyingImageBackgroundSkia : ContentView
{
public static readonly BindableProperty IsActiveProperty =
BindableProperty.Create(
nameof(IsActive),
typeof(bool),
typeof(FlyingImageBackground),
default(bool),
BindingMode.TwoWay,
propertyChanged: OnPageActivenessChanged);
private SKCanvasView canvasView;
private SKBitmap resourceBitmap;
private Stopwatch stopwatch = new Stopwatch();
// consider making these bindable props
private float percentComplete;
private float imageSize = 40;
private float columnSpacing = 100;
private float rowSpacing = 100;
private float framesPerSecond = 60;
private float cycleTime = 1; // in seconds, for a single column
public FlyingImageBackgroundSkia()
{
this.canvasView = new SKCanvasView();
this.canvasView.PaintSurface += OnCanvasViewPaintSurface;
this.Content = this.canvasView;
string resourceID = "XamarinTestProject.Resources.Images.fireTruck.png";
Assembly assembly = GetType().GetTypeInfo().Assembly;
using (Stream stream = assembly.GetManifestResourceStream(resourceID))
{
this.resourceBitmap = SKBitmap.Decode(stream);
}
}
~FlyingImageBackgroundSkia() => this.resourceBitmap.Dispose();
public bool IsActive
{
get => (bool)GetValue(IsActiveProperty);
set => SetValue(IsActiveProperty, value);
}
private static async void OnPageActivenessChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (FlyingImageBackgroundSkia)bindable;
await control.AnimationLoop();
}
private async Task AnimationLoop()
{
this.stopwatch.Start();
while (IsActive)
{
this.percentComplete = (float)(this.stopwatch.Elapsed.TotalSeconds % this.cycleTime) / this.cycleTime; // always between 0 and 1
this.canvasView.InvalidateSurface(); // trigger redraw
await Task.Delay(TimeSpan.FromSeconds(1.0 / this.framesPerSecond)); // non-blocking
}
this.stopwatch.Stop();
}
private void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
var xPositions = Enumerable.Range(0, info.Width + (int)this.columnSpacing).Where(x => x % (int)this.columnSpacing == 0).ToList();
xPositions.Insert(0, -(int)this.columnSpacing);
var yPositions = Enumerable.Range(0, info.Height + (int)this.rowSpacing).Where(x => x % (int)this.rowSpacing == 0).ToList();
yPositions.Insert(0, -(int)this.rowSpacing);
if (this.resourceBitmap != null)
{
foreach (var xPos in xPositions)
{
var xPosNow = xPos + (this.rowSpacing * this.percentComplete);
foreach (var yPos in yPositions)
{
canvas.DrawBitmap(
this.resourceBitmap,
new SKRect(xPosNow, yPos, xPosNow + this.imageSize, yPos + this.imageSize));
}
}
}
}
}

OutOfMemoryException in Windows Phone app

i make gallery in my app
when i back and choose another album system.OutOfMemoryException occurs
this is my Xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ScrollViewer Margin="0,1,0,71" >
<Grid Width="475" Name="picbtn" Background="WhiteSmoke" >
</Grid>
</ScrollViewer>
</Grid>
this is my code
string type;
int x = 0;
int y = 4050;
int i = 0;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.NavigationMode != NavigationMode.Back)
{
type = NavigationContext.QueryString["name"];
ReadFromXml(type);
}
}
private void ReadFromXml(string type)
{
XDocument xml;
if (type == "day")
{
xml = XDocument.Load("DayimagesData.xml");
}
else
{
xml = XDocument.Load("NightmagesData.xml");
}
var query = from c in xml.Root.Descendants("posts")
select c.Element("image").Value;
foreach (var name in query)
{
CreateGrid(name);
i++;
if (i % 3 == 0)
{
x += 150;
y -= 150;
}
}
}
private void CreateGrid(string data)
{
BitmapImage image = new BitmapImage(
new Uri(#"images\" + data, UriKind.Relative)
);
Grid g1 = new Grid
{
Width = 150,
Height = 150,
Margin = new Thickness(0, x, 0, y),
DataContext = data
};
Image im = new Image
{
Source = image
};
g1.Children.Add(im);
if (i % 3 == 0)
{ g1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; }
else if (i % 3 == 1)
{
g1.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
}
else
{
g1.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
}
picbtn.Children.Add(g1);
g1.Tap += Grid_Tap;
}
is there are any method to clear the memory when the back clicked ??
i try
GC.collect
but the same issue happened
Dispose XDocument and BitmapImage properly .From your code those are the memory consumers on high note.

Pan & Zoom Image

I want to create a simple image viewer in WPF that will enable the user to:
Pan (by mouse dragging the image).
Zoom (with a slider).
Show overlays (rectangle selection for example).
Show original image (with scroll bars if needed).
Can you explain how to do it?
I didn't find a good sample on the web.
Should I use ViewBox? Or ImageBrush?
Do I need ScrollViewer?
After using samples from this question I've made complete version of pan & zoom app with proper zooming relative to mouse pointer. All pan & zoom code has been moved to separate class called ZoomBorder.
ZoomBorder.cs
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace PanAndZoom
{
public class ZoomBorder : Border
{
private UIElement child = null;
private Point origin;
private Point start;
private TranslateTransform GetTranslateTransform(UIElement element)
{
return (TranslateTransform)((TransformGroup)element.RenderTransform)
.Children.First(tr => tr is TranslateTransform);
}
private ScaleTransform GetScaleTransform(UIElement element)
{
return (ScaleTransform)((TransformGroup)element.RenderTransform)
.Children.First(tr => tr is ScaleTransform);
}
public override UIElement Child
{
get { return base.Child; }
set
{
if (value != null && value != this.Child)
this.Initialize(value);
base.Child = value;
}
}
public void Initialize(UIElement element)
{
this.child = element;
if (child != null)
{
TransformGroup group = new TransformGroup();
ScaleTransform st = new ScaleTransform();
group.Children.Add(st);
TranslateTransform tt = new TranslateTransform();
group.Children.Add(tt);
child.RenderTransform = group;
child.RenderTransformOrigin = new Point(0.0, 0.0);
this.MouseWheel += child_MouseWheel;
this.MouseLeftButtonDown += child_MouseLeftButtonDown;
this.MouseLeftButtonUp += child_MouseLeftButtonUp;
this.MouseMove += child_MouseMove;
this.PreviewMouseRightButtonDown += new MouseButtonEventHandler(
child_PreviewMouseRightButtonDown);
}
}
public void Reset()
{
if (child != null)
{
// reset zoom
var st = GetScaleTransform(child);
st.ScaleX = 1.0;
st.ScaleY = 1.0;
// reset pan
var tt = GetTranslateTransform(child);
tt.X = 0.0;
tt.Y = 0.0;
}
}
#region Child Events
private void child_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (child != null)
{
var st = GetScaleTransform(child);
var tt = GetTranslateTransform(child);
double zoom = e.Delta > 0 ? .2 : -.2;
if (!(e.Delta > 0) && (st.ScaleX < .4 || st.ScaleY < .4))
return;
Point relative = e.GetPosition(child);
double absoluteX;
double absoluteY;
absoluteX = relative.X * st.ScaleX + tt.X;
absoluteY = relative.Y * st.ScaleY + tt.Y;
st.ScaleX += zoom;
st.ScaleY += zoom;
tt.X = absoluteX - relative.X * st.ScaleX;
tt.Y = absoluteY - relative.Y * st.ScaleY;
}
}
private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (child != null)
{
var tt = GetTranslateTransform(child);
start = e.GetPosition(this);
origin = new Point(tt.X, tt.Y);
this.Cursor = Cursors.Hand;
child.CaptureMouse();
}
}
private void child_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (child != null)
{
child.ReleaseMouseCapture();
this.Cursor = Cursors.Arrow;
}
}
void child_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
this.Reset();
}
private void child_MouseMove(object sender, MouseEventArgs e)
{
if (child != null)
{
if (child.IsMouseCaptured)
{
var tt = GetTranslateTransform(child);
Vector v = start - e.GetPosition(this);
tt.X = origin.X - v.X;
tt.Y = origin.Y - v.Y;
}
}
}
#endregion
}
}
MainWindow.xaml
<Window x:Class="PanAndZoom.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PanAndZoom"
Title="PanAndZoom" Height="600" Width="900" WindowStartupLocation="CenterScreen">
<Grid>
<local:ZoomBorder x:Name="border" ClipToBounds="True" Background="Gray">
<Image Source="image.jpg"/>
</local:ZoomBorder>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
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.Navigation;
using System.Windows.Shapes;
namespace PanAndZoom
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
The way I solved this problem was to place the image within a Border with it's ClipToBounds property set to True. The RenderTransformOrigin on the image is then set to 0.5,0.5 so the image will start zooming on the center of the image. The RenderTransform is also set to a TransformGroup containing a ScaleTransform and a TranslateTransform.
I then handled the MouseWheel event on the image to implement zooming
private void image_MouseWheel(object sender, MouseWheelEventArgs e)
{
var st = (ScaleTransform)image.RenderTransform;
double zoom = e.Delta > 0 ? .2 : -.2;
st.ScaleX += zoom;
st.ScaleY += zoom;
}
To handle the panning the first thing I did was to handle the MouseLeftButtonDown event on the image, to capture the mouse and to record it's location, I also store the current value of the TranslateTransform, this what is updated to implement panning.
Point start;
Point origin;
private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
image.CaptureMouse();
var tt = (TranslateTransform)((TransformGroup)image.RenderTransform)
.Children.First(tr => tr is TranslateTransform);
start = e.GetPosition(border);
origin = new Point(tt.X, tt.Y);
}
Then I handled the MouseMove event to update the TranslateTransform.
private void image_MouseMove(object sender, MouseEventArgs e)
{
if (image.IsMouseCaptured)
{
var tt = (TranslateTransform)((TransformGroup)image.RenderTransform)
.Children.First(tr => tr is TranslateTransform);
Vector v = start - e.GetPosition(border);
tt.X = origin.X - v.X;
tt.Y = origin.Y - v.Y;
}
}
Finally don't forget to release the mouse capture.
private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
image.ReleaseMouseCapture();
}
As for the selection handles for resizing this can be accomplished using an adorner, check out this article for more information.
The answer was posted above but wasn't complete. here is the completed version:
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MapTest.Window1"
x:Name="Window"
Title="Window1"
Width="1950" Height="1546" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:Controls="clr-namespace:WPFExtensions.Controls;assembly=WPFExtensions" mc:Ignorable="d" Background="#FF000000">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="52.92"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="1" Name="border">
<Image Name="image" Source="map3-2.png" Opacity="1" RenderTransformOrigin="0.5,0.5" />
</Border>
</Grid>
Code Behind
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace MapTest
{
public partial class Window1 : Window
{
private Point origin;
private Point start;
public Window1()
{
InitializeComponent();
TransformGroup group = new TransformGroup();
ScaleTransform xform = new ScaleTransform();
group.Children.Add(xform);
TranslateTransform tt = new TranslateTransform();
group.Children.Add(tt);
image.RenderTransform = group;
image.MouseWheel += image_MouseWheel;
image.MouseLeftButtonDown += image_MouseLeftButtonDown;
image.MouseLeftButtonUp += image_MouseLeftButtonUp;
image.MouseMove += image_MouseMove;
}
private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
image.ReleaseMouseCapture();
}
private void image_MouseMove(object sender, MouseEventArgs e)
{
if (!image.IsMouseCaptured) return;
var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
Vector v = start - e.GetPosition(border);
tt.X = origin.X - v.X;
tt.Y = origin.Y - v.Y;
}
private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
image.CaptureMouse();
var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
start = e.GetPosition(border);
origin = new Point(tt.X, tt.Y);
}
private void image_MouseWheel(object sender, MouseWheelEventArgs e)
{
TransformGroup transformGroup = (TransformGroup) image.RenderTransform;
ScaleTransform transform = (ScaleTransform) transformGroup.Children[0];
double zoom = e.Delta > 0 ? .2 : -.2;
transform.ScaleX += zoom;
transform.ScaleY += zoom;
}
}
}
I have some source code demonstrating this Jot the sticky note app.
Pan: Put the image inside of a Canvas. Implement Mouse Up, Down, and Move events to move the Canvas.Top, Canvas.Left properties. When down, you mark a isDraggingFlag to true, when up you set the flag to false. On move, you check if the flag is set, if it is you offset the Canvas.Top and Canvas.Left properties on the image within the canvas.
Zoom: Bind the slider to the Scale Transform of the Canvas
Show overlays: add additional canvas's with no background ontop the canvas containing the image.
show original image: image control inside of a ViewBox
Try this Zoom Control: http://wpfextensions.codeplex.com
usage of the control is very simple, reference to the wpfextensions assembly than:
<wpfext:ZoomControl>
<Image Source="..."/>
</wpfext:ZoomControl>
Scrollbars not supported at this moment. (It will be in the next release which will be available in one or two week).
#Anothen and #Number8 - The Vector class is not available in Silverlight, so to make it work we just need to keep a record of the last position sighted the last time the MouseMove event was called, and compare the two points to find the difference; then adjust the transform.
XAML:
<Border Name="viewboxBackground" Background="Black">
<Viewbox Name="viewboxMain">
<!--contents go here-->
</Viewbox>
</Border>
Code-behind:
public Point _mouseClickPos;
public bool bMoving;
public MainPage()
{
InitializeComponent();
viewboxMain.RenderTransform = new CompositeTransform();
}
void MouseMoveHandler(object sender, MouseEventArgs e)
{
if (bMoving)
{
//get current transform
CompositeTransform transform = viewboxMain.RenderTransform as CompositeTransform;
Point currentPos = e.GetPosition(viewboxBackground);
transform.TranslateX += (currentPos.X - _mouseClickPos.X) ;
transform.TranslateY += (currentPos.Y - _mouseClickPos.Y) ;
viewboxMain.RenderTransform = transform;
_mouseClickPos = currentPos;
}
}
void MouseClickHandler(object sender, MouseButtonEventArgs e)
{
_mouseClickPos = e.GetPosition(viewboxBackground);
bMoving = true;
}
void MouseReleaseHandler(object sender, MouseButtonEventArgs e)
{
bMoving = false;
}
Also note that you don't need a TransformGroup or collection to implement pan and zoom; instead, a CompositeTransform will do the trick with less hassle.
I'm pretty sure this is really inefficient in terms of resource usage, but at least it works :)
To zoom relative to the mouse position, all you need is:
var position = e.GetPosition(image1);
image1.RenderTransformOrigin = new Point(position.X / image1.ActualWidth, position.Y / image1.ActualHeight);
I also tried this answer but was not entirely happy with the result. I kept googling around and finally found a Nuget Package that helped me to manage the result I wanted, anno 2021. I would like to share it with the former developers of Stack Overflow.
I used this Nuget Package Gu.WPF.Geometry found via this Github Repository. All credits for develoment should go to Johan Larsson, the owner of this package.
How I used it? I wanted to have the commands as buttons below the zoombox, as shown here in MachineLayoutControl.xaml .
<UserControl
x:Class="MyLib.MachineLayoutControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:csmachinelayoutdrawlib="clr-namespace:CSMachineLayoutDrawLib"
xmlns:effects="http://gu.se/Geometry">
<UserControl.Resources>
<ResourceDictionary Source="Resources/ResourceDictionaries/AllResourceDictionariesCombined.xaml" />
</UserControl.Resources>
<Grid Margin="0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border
Grid.Row="0"
Margin="0,0"
Padding="0"
BorderThickness="1"
Style="{StaticResource Border_Head}"
Visibility="Visible">
<effects:Zoombox
x:Name="ImageBox"
IsManipulationEnabled="True"
MaxZoom="10"
MinZoom="0.1"
Visibility="{Binding Zoombox_Visibility}">
<ContentControl Content="{Binding Viewing_Canvas}" />
</effects:Zoombox>
</Border>
<StackPanel
Grid.Column="1"
Margin="10"
HorizontalAlignment="Right"
Orientation="Horizontal">
<Button
Command="effects:ZoomCommands.Increase"
CommandParameter="2.0"
CommandTarget="{Binding ElementName=ImageBox}"
Content="Zoom In"
Style="{StaticResource StyleForResizeButtons}" />
<Button
Command="effects:ZoomCommands.Decrease"
CommandParameter="2.0"
CommandTarget="{Binding ElementName=ImageBox}"
Content="Zoom Out"
Style="{StaticResource StyleForResizeButtons}" />
<Button
Command="effects:ZoomCommands.Uniform"
CommandTarget="{Binding ElementName=ImageBox}"
Content="See Full Machine"
Style="{StaticResource StyleForResizeButtons}" />
<Button
Command="effects:ZoomCommands.UniformToFill"
CommandTarget="{Binding ElementName=ImageBox}"
Content="Zoom To Machine Width"
Style="{StaticResource StyleForResizeButtons}" />
</StackPanel>
</Grid>
</UserControl>
In the underlying Viewmodel, I had the following relevant code:
public Visibility Zoombox_Visibility { get => movZoombox_Visibility; set { movZoombox_Visibility = value; OnPropertyChanged(nameof(Zoombox_Visibility)); } }
public Canvas Viewing_Canvas { get => mdvViewing_Canvas; private set => mdvViewing_Canvas = value; }
Also, I wanted that immediately on loading, the Uniform to Fill Command was executed, this is something that I managed to do in the code-behind MachineLayoutControl.xaml.cs . You see that I only set the Zoombox to visible if the command is executed, to avoid "flickering" when the usercontrol is loading.
public partial class MachineLayoutControl : UserControl
{
#region Constructors
public MachineLayoutControl()
{
InitializeComponent();
Loaded += MyWindow_Loaded;
}
#endregion Constructors
#region EventHandlers
private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.ApplicationIdle,
new Action(() =>
{
ZoomCommands.Uniform.Execute(null, ImageBox);
((MachineLayoutControlViewModel)DataContext).Zoombox_Visibility = Visibility.Visible;
}));
}
#endregion EventHandlers
}
# Merk
For ur solution insted of lambda expression you can use following code:
//var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
TranslateTransform tt = null;
TransformGroup transformGroup = (TransformGroup)grid.RenderTransform;
for (int i = 0; i < transformGroup.Children.Count; i++)
{
if (transformGroup.Children[i] is TranslateTransform)
tt = (TranslateTransform)transformGroup.Children[i];
}
this code can be use as is for .Net Frame work 3.0 or 2.0
Hope It helps you :-)
Yet another version of the same kind of control. It has similar functionality as the others, but it adds:
Touch support (drag/pinch)
The image can be deleted (normally, the Image control locks the image on disk, so you cannot delete it).
An inner border child, so the panned image doesn't overlap the border. In case of borders with rounded rectangles, look for ClippedBorder classes.
Usage is simple:
<Controls:ImageViewControl ImagePath="{Binding ...}" />
And the code:
public class ImageViewControl : Border
{
private Point origin;
private Point start;
private Image image;
public ImageViewControl()
{
ClipToBounds = true;
Loaded += OnLoaded;
}
#region ImagePath
/// <summary>
/// ImagePath Dependency Property
/// </summary>
public static readonly DependencyProperty ImagePathProperty = DependencyProperty.Register("ImagePath", typeof (string), typeof (ImageViewControl), new FrameworkPropertyMetadata(string.Empty, OnImagePathChanged));
/// <summary>
/// Gets or sets the ImagePath property. This dependency property
/// indicates the path to the image file.
/// </summary>
public string ImagePath
{
get { return (string) GetValue(ImagePathProperty); }
set { SetValue(ImagePathProperty, value); }
}
/// <summary>
/// Handles changes to the ImagePath property.
/// </summary>
private static void OnImagePathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var target = (ImageViewControl) d;
var oldImagePath = (string) e.OldValue;
var newImagePath = target.ImagePath;
target.ReloadImage(newImagePath);
target.OnImagePathChanged(oldImagePath, newImagePath);
}
/// <summary>
/// Provides derived classes an opportunity to handle changes to the ImagePath property.
/// </summary>
protected virtual void OnImagePathChanged(string oldImagePath, string newImagePath)
{
}
#endregion
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
image = new Image {
//IsManipulationEnabled = true,
RenderTransformOrigin = new Point(0.5, 0.5),
RenderTransform = new TransformGroup {
Children = new TransformCollection {
new ScaleTransform(),
new TranslateTransform()
}
}
};
// NOTE I use a border as the first child, to which I add the image. I do this so the panned image doesn't partly obscure the control's border.
// In case you are going to use rounder corner's on this control, you may to update your clipping, as in this example:
// http://wpfspark.wordpress.com/2011/06/08/clipborder-a-wpf-border-that-clips/
var border = new Border {
IsManipulationEnabled = true,
ClipToBounds = true,
Child = image
};
Child = border;
image.MouseWheel += (s, e) =>
{
var zoom = e.Delta > 0
? .2
: -.2;
var position = e.GetPosition(image);
image.RenderTransformOrigin = new Point(position.X / image.ActualWidth, position.Y / image.ActualHeight);
var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
st.ScaleX += zoom;
st.ScaleY += zoom;
e.Handled = true;
};
image.MouseLeftButtonDown += (s, e) =>
{
if (e.ClickCount == 2)
ResetPanZoom();
else
{
image.CaptureMouse();
var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
start = e.GetPosition(this);
origin = new Point(tt.X, tt.Y);
}
e.Handled = true;
};
image.MouseMove += (s, e) =>
{
if (!image.IsMouseCaptured) return;
var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
var v = start - e.GetPosition(this);
tt.X = origin.X - v.X;
tt.Y = origin.Y - v.Y;
e.Handled = true;
};
image.MouseLeftButtonUp += (s, e) => image.ReleaseMouseCapture();
//NOTE I apply the manipulation to the border, and not to the image itself (which caused stability issues when translating)!
border.ManipulationDelta += (o, e) =>
{
var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
st.ScaleX *= e.DeltaManipulation.Scale.X;
st.ScaleY *= e.DeltaManipulation.Scale.X;
tt.X += e.DeltaManipulation.Translation.X;
tt.Y += e.DeltaManipulation.Translation.Y;
e.Handled = true;
};
}
private void ResetPanZoom()
{
var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
st.ScaleX = st.ScaleY = 1;
tt.X = tt.Y = 0;
image.RenderTransformOrigin = new Point(0.5, 0.5);
}
/// <summary>
/// Load the image (and do not keep a hold on it, so we can delete the image without problems)
/// </summary>
/// <see cref="http://blogs.vertigo.com/personal/ralph/Blog/Lists/Posts/Post.aspx?ID=18"/>
/// <param name="path"></param>
private void ReloadImage(string path)
{
try
{
ResetPanZoom();
// load the image, specify CacheOption so the file is not locked
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
bitmapImage.EndInit();
image.Source = bitmapImage;
}
catch (SystemException e)
{
Console.WriteLine(e.Message);
}
}
}
This will zoom in and out as well as pan but keep the image within the bounds of the container. Written as a control so add the style to the App.xaml directly or through the Themes/Viewport.xaml.
For readability I've also uploaded this on gist and github
I've also packaged this up on nuget
PM > Install-Package Han.Wpf.ViewportControl
./Controls/Viewport.cs:
public class Viewport : ContentControl
{
private bool _capture;
private FrameworkElement _content;
private Matrix _matrix;
private Point _origin;
public static readonly DependencyProperty MaxZoomProperty =
DependencyProperty.Register(
nameof(MaxZoom),
typeof(double),
typeof(Viewport),
new PropertyMetadata(0d));
public static readonly DependencyProperty MinZoomProperty =
DependencyProperty.Register(
nameof(MinZoom),
typeof(double),
typeof(Viewport),
new PropertyMetadata(0d));
public static readonly DependencyProperty ZoomSpeedProperty =
DependencyProperty.Register(
nameof(ZoomSpeed),
typeof(float),
typeof(Viewport),
new PropertyMetadata(0f));
public static readonly DependencyProperty ZoomXProperty =
DependencyProperty.Register(
nameof(ZoomX),
typeof(double),
typeof(Viewport),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty ZoomYProperty =
DependencyProperty.Register(
nameof(ZoomY),
typeof(double),
typeof(Viewport),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty OffsetXProperty =
DependencyProperty.Register(
nameof(OffsetX),
typeof(double),
typeof(Viewport),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty OffsetYProperty =
DependencyProperty.Register(
nameof(OffsetY),
typeof(double),
typeof(Viewport),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty BoundsProperty =
DependencyProperty.Register(
nameof(Bounds),
typeof(Rect),
typeof(Viewport),
new FrameworkPropertyMetadata(default(Rect), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public Rect Bounds
{
get => (Rect) GetValue(BoundsProperty);
set => SetValue(BoundsProperty, value);
}
public double MaxZoom
{
get => (double) GetValue(MaxZoomProperty);
set => SetValue(MaxZoomProperty, value);
}
public double MinZoom
{
get => (double) GetValue(MinZoomProperty);
set => SetValue(MinZoomProperty, value);
}
public double OffsetX
{
get => (double) GetValue(OffsetXProperty);
set => SetValue(OffsetXProperty, value);
}
public double OffsetY
{
get => (double) GetValue(OffsetYProperty);
set => SetValue(OffsetYProperty, value);
}
public float ZoomSpeed
{
get => (float) GetValue(ZoomSpeedProperty);
set => SetValue(ZoomSpeedProperty, value);
}
public double ZoomX
{
get => (double) GetValue(ZoomXProperty);
set => SetValue(ZoomXProperty, value);
}
public double ZoomY
{
get => (double) GetValue(ZoomYProperty);
set => SetValue(ZoomYProperty, value);
}
public Viewport()
{
DefaultStyleKey = typeof(Viewport);
Loaded += OnLoaded;
Unloaded += OnUnloaded;
}
private void Arrange(Size desired, Size render)
{
_matrix = Matrix.Identity;
var zx = desired.Width / render.Width;
var zy = desired.Height / render.Height;
var cx = render.Width < desired.Width ? render.Width / 2.0 : 0.0;
var cy = render.Height < desired.Height ? render.Height / 2.0 : 0.0;
var zoom = Math.Min(zx, zy);
if (render.Width > desired.Width &&
render.Height > desired.Height)
{
cx = (desired.Width - (render.Width * zoom)) / 2.0;
cy = (desired.Height - (render.Height * zoom)) / 2.0;
_matrix = new Matrix(zoom, 0d, 0d, zoom, cx, cy);
}
else
{
_matrix.ScaleAt(zoom, zoom, cx, cy);
}
}
private void Attach(FrameworkElement content)
{
content.MouseMove += OnMouseMove;
content.MouseLeave += OnMouseLeave;
content.MouseWheel += OnMouseWheel;
content.MouseLeftButtonDown += OnMouseLeftButtonDown;
content.MouseLeftButtonUp += OnMouseLeftButtonUp;
content.SizeChanged += OnSizeChanged;
content.MouseRightButtonDown += OnMouseRightButtonDown;
}
private void ChangeContent(FrameworkElement content)
{
if (content != null && !Equals(content, _content))
{
if (_content != null)
{
Detatch();
}
Attach(content);
_content = content;
}
}
private double Constrain(double value, double min, double max)
{
if (min > max)
{
min = max;
}
if (value <= min)
{
return min;
}
if (value >= max)
{
return max;
}
return value;
}
private void Constrain()
{
var x = Constrain(_matrix.OffsetX, _content.ActualWidth - _content.ActualWidth * _matrix.M11, 0);
var y = Constrain(_matrix.OffsetY, _content.ActualHeight - _content.ActualHeight * _matrix.M22, 0);
_matrix = new Matrix(_matrix.M11, 0d, 0d, _matrix.M22, x, y);
}
private void Detatch()
{
_content.MouseMove -= OnMouseMove;
_content.MouseLeave -= OnMouseLeave;
_content.MouseWheel -= OnMouseWheel;
_content.MouseLeftButtonDown -= OnMouseLeftButtonDown;
_content.MouseLeftButtonUp -= OnMouseLeftButtonUp;
_content.SizeChanged -= OnSizeChanged;
_content.MouseRightButtonDown -= OnMouseRightButtonDown;
}
private void Invalidate()
{
if (_content != null)
{
Constrain();
_content.RenderTransformOrigin = new Point(0, 0);
_content.RenderTransform = new MatrixTransform(_matrix);
_content.InvalidateVisual();
ZoomX = _matrix.M11;
ZoomY = _matrix.M22;
OffsetX = _matrix.OffsetX;
OffsetY = _matrix.OffsetY;
var rect = new Rect
{
X = OffsetX * -1,
Y = OffsetY * -1,
Width = ActualWidth,
Height = ActualHeight
};
Bounds = rect;
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_matrix = Matrix.Identity;
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
if (Content is FrameworkElement element)
{
ChangeContent(element);
}
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (Content is FrameworkElement element)
{
ChangeContent(element);
}
SizeChanged += OnSizeChanged;
Loaded -= OnLoaded;
}
private void OnMouseLeave(object sender, MouseEventArgs e)
{
if (_capture)
{
Released();
}
}
private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (IsEnabled && !_capture)
{
Pressed(e.GetPosition(this));
}
}
private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (IsEnabled && _capture)
{
Released();
}
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (IsEnabled && _capture)
{
var position = e.GetPosition(this);
var point = new Point
{
X = position.X - _origin.X,
Y = position.Y - _origin.Y
};
var delta = point;
_origin = position;
_matrix.Translate(delta.X, delta.Y);
Invalidate();
}
}
private void OnMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
if (IsEnabled)
{
Reset();
}
}
private void OnMouseWheel(object sender, MouseWheelEventArgs e)
{
if (IsEnabled)
{
var scale = e.Delta > 0 ? ZoomSpeed : 1 / ZoomSpeed;
var position = e.GetPosition(_content);
var x = Constrain(scale, MinZoom / _matrix.M11, MaxZoom / _matrix.M11);
var y = Constrain(scale, MinZoom / _matrix.M22, MaxZoom / _matrix.M22);
_matrix.ScaleAtPrepend(x, y, position.X, position.Y);
ZoomX = _matrix.M11;
ZoomY = _matrix.M22;
Invalidate();
}
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
if (_content?.IsMeasureValid ?? false)
{
Arrange(_content.DesiredSize, _content.RenderSize);
Invalidate();
}
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
Detatch();
SizeChanged -= OnSizeChanged;
Unloaded -= OnUnloaded;
}
private void Pressed(Point position)
{
if (IsEnabled)
{
_content.Cursor = Cursors.Hand;
_origin = position;
_capture = true;
}
}
private void Released()
{
if (IsEnabled)
{
_content.Cursor = null;
_capture = false;
}
}
private void Reset()
{
_matrix = Matrix.Identity;
if (_content != null)
{
Arrange(_content.DesiredSize, _content.RenderSize);
}
Invalidate();
}
}
./Themes/Viewport.xaml:
<ResourceDictionary ... >
<Style TargetType="{x:Type controls:Viewport}"
BasedOn="{StaticResource {x:Type ContentControl}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:Viewport}">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}">
<Grid ClipToBounds="True"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}">
<Grid x:Name="PART_Container">
<ContentPresenter x:Name="PART_Presenter" />
</Grid>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
./App.xaml
<Application ... >
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="./Themes/Viewport.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Usage:
<viewers:Viewport>
<Image Source="{Binding}"/>
</viewers:Viewport>
Any issues, give me a shout.
Happy coding :)
One addition to the superb solution provided by #Wiesław Šoltés answer above
The existing code resets the image position using right click, but I am more accustomed to doing that with a double click. Just replace the existing child_MouseLeftButtonDown handler:
private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (child != null)
{
var tt = GetTranslateTransform(child);
start = e.GetPosition(this);
origin = new Point(tt.X, tt.Y);
this.Cursor = Cursors.Hand;
child.CaptureMouse();
}
}
With this:
private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 1))
{
if (child != null)
{
var tt = GetTranslateTransform(child);
start = e.GetPosition(this);
origin = new Point(tt.X, tt.Y);
this.Cursor = Cursors.Hand;
child.CaptureMouse();
}
}
if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 2))
{
this.Reset();
}
}

Categories