I am trying to load a picture into the Image UI item of my win8 app. But so far i couldn't get the picked image to show on the UI.
can somebody please tell me how the proper way of doing it?
Windows.Storage.Pickers.FileOpenPicker OpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
OpenPicker.FileTypeFilter.Add(".jpg");
OpenPicker.FileTypeFilter.Add(".bmp");
Windows.Storage.StorageFile picture = await OpenPicker.PickSingleFileAsync();
imgPreview.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(picture.Path, UriKind.Absolute));
imgPreview.Stretch = Stretch.Fill;
imgPreview.Visibility = Windows.UI.Xaml.Visibility.Visible;
See my post on this here.
It should be something like this:
xaml:
<Image Margin="5" Source="{Binding BMImage}" Height="100"/>
C#:
BitmapImage bmImage;
public BitmapImage BMImage
{
get
{
return bmImage;
}
}
bmImage = new BitmapImage();
bmImage.UriSource = new Uri(new Uri(
Windows.Storage.ApplicationData.Current.TemporaryFolder.Path + "\\" +
Windows.Storage.ApplicationData.Current.TemporaryFolder.Name),
"favicon.scale-100.ico");
Related
I'm trying:
<Image Source="/storage/emulated/0/Pictures/Test/IMG_20200408_085036.jpg"/>
No effect.
File imageSpc = new File('/storage/emulated/0/Pictures/Test/IMG_20200408_085036.jpg');
var imageSpc = new File('/storage/emulated/0/Pictures/Test/IMG_20200408_085036.jpg');
Error, cannot create static variable for type File or var.
<Image x:Name="fotka" Aspect="AspectFit" HeightRequest = "50"
WidthRequest = "60"/>
fotka.Source = ImageSource.FromFile("/storage/emulated/0/Pictures/Test/IMG_20200408_085036.jpg");
No effect
Is possible to show specific image from gallery in XAML or at least from the code
I did enable ADB notification option in device.
In The moment image to be displayed compiler show error:
How to fix this Error?
According to your description, you want to display image using gallery path, if yes, please take a look the following code:
Firstly, you need to get image path from gallery in Android or ios.
Create interface IFileSystem in PCL(Forms)
public interface IFileSystem
{
string GetGalleryImage();
}
Then implementing this interface in platform, the example is in Android.
[assembly: Dependency(typeof(FileSystemImplementation))]
namespace demo3.Droid
{
public class FileSystemImplementation : IFileSystem
{
public string GetGalleryImage()
{
var filePath = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures);
var path = System.IO.Path.Combine(filePath.AbsolutePath, "Test/image1.jpg");
return path;
}
}
}
Add one Image control in PCL(Forms), name image1, using DependencyService to get image path.
<Button
x:Name="btn1"
Clicked="Btn1_Clicked"
Text="load image" />
<Image
x:Name="image1"
HeightRequest="100"
WidthRequest="100" />
private void Btn1_Clicked(object sender, EventArgs e)
{
var path = DependencyService.Get<IFileSystem>().GetGalleryImage();
image1.Source = ImageSource.FromFile(path);
}
This is article about DependencyService, you can take a look:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction
Update:
I found, each image before show in activity must be resized to max size 4096 x 4096 px otherwise image not shown, without any errors message.
I have a Xamarin.Forms page written in .xaml On iOS platform only I am trying to wrap the content of the page in ScrollView to help fix resizing issue when keyboard is shown.
The page looks something like this:
<base:mypagebase...>
<ContentPage.Resources>
...
</ContentPage.Resources>
<ContentPage.Content>
<RelativeLayout x:Name="ViewContentLayout" VerticalOptions="FillAndExpand">
....
</RelativeLayou>
</ContentPage.Content>
</base:mypagebase>
I am trying in the constructor of my mpage.xaml.cs after InitializeComponent() to wrap my RelativeLayout in ScrollView
Something like this:
if (Device.RuntimePlatform == Device.iOS)
{
var scroll = new ScrollView();
scroll.Orientation = ScrollOrientation.Vertical;
scroll.VerticalOptions = LayoutOptions.FillAndExpand;
scroll.Content = ViewContentLayout;
Content = scroll;
}
It passes through but throws exception later:
Object reference not set to an instance of an object
at Xamarin.Forms.RelativeLayout.OnSizeRequest (System.Double widthConstraint, System.Double heightConstraint) [0x00017] in RelativeLayout.cs:185
The order in which the properties are called matters, seems like the Content root had to be set first:
if (Device.RuntimePlatform == Device.iOS)
{
var viewContentLayout = ViewContentLayout;
var scroll = new ScrollView();
Content = scroll;
scroll.Content = viewContentLayout;
}
I need the pdf viewer side by side of my app, so that i will be able to view the pdf generated when any changes made in app. In windows 8.1 app the PDF is opened using Reader app and by default it opens PDF side by side.
But the case in Win10 is not the same. In win 10 the reader app is opened seperately pushing back the app screen.Is there any similar viewer as like in win 8.1
Below image is from windows 8.1 app
Here is the solution to open PDF files inside the app
As usual I opened PDF from files as storage file.
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/pdffile.pdf"));
Windows.Data.Pdf.PdfDocument doc = await Windows.Data.Pdf.PdfDocument.LoadFromFileAsync(file);
Load(doc);
Now the PDF document is read page by page as BitmapImage and added to a list.
public async void Load(PdfDocument pdfDoc)
{
PdfPages.Clear();
for (uint i = 0; i < pdfDoc.PageCount; i++)
{
BitmapImage image = new BitmapImage();
var page = pdfDoc.GetPage(i);
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
await page.RenderToStreamAsync(stream);
await image.SetSourceAsync(stream);
}
PdfPages.Add(image);
}
}
public ObservableCollection<BitmapImage> PdfDocPages
{
get;
set;
} = new ObservableCollection<BitmapImage>();
Binding the ObservableCollection to the ItemsControl we can view the PDF as images.
<ScrollViewer ZoomMode="Enabled" Background="DarkGray" Grid.Column="1">
<ItemsControl ItemsSource="{Binding PdfDocPages, ElementName=pageRoot}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}" Margin="0 2" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
I am making a Windows 8 application in visual studio 2012 c#.
I am having an image '1.png' and I want to rotate it at any angle as an animation along its center point.
But i want to do it with the help of c# code rather than XAML code.
Thank You in Advance.
In your XAML, have the following image:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Image Source="/Assets/Logo.png" Width="300" RenderTransformOrigin="0.5, 0.5">
<Image.RenderTransform>
<RotateTransform x:Name="rotateTransform"/>
</Image.RenderTransform>
</Image>
</Grid>
Then, in code, write the following when you want to animate (you create the Storyboard programmatically, then add to it a relevant Timeline. Note that you can also create the RotateTransform in code if you want.
async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
await Task.Delay(500);
Storyboard board = new Storyboard();
var timeline = new DoubleAnimationUsingKeyFrames();
Storyboard.SetTarget(timeline, rotateTransform);
Storyboard.SetTargetProperty(timeline, "Angle");
var frame = new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(1), Value = 360, EasingFunction = new QuadraticEase() { EasingMode = EasingMode.EaseOut } };
timeline.KeyFrames.Add(frame);
board.Children.Add(timeline);
board.Begin();
}
This will rotate the object 360 degrees.
BTW: I am writing a set of posts that show an even better way of animating. It's not done yet, but it will give you a general idea on how to get a framework for certain types of animations..
First part of the series
Thanks Shahar! I took your example and made a custom control. It's actually an infinite spinning of one ring image.
Spinner.xaml:
<UserControl x:Class="MyControls.Spinner"
...
<Grid >
<Image Source="/Assets/Images/spinner.png" Width="194" RenderTransformOrigin="0.5, 0.5">
<Image.RenderTransform>
<RotateTransform x:Name="rotateTransform"/>
</Image.RenderTransform>
</Image>
</Grid>
</UserControl>
Spinner.cs:
namespace MyControls
{
public partial class Spinner: UserControl
{
public Spinner()
{
InitializeComponent();
this.Loaded += Spinner_Loaded;
}
private void PlayRotation()
{
Storyboard board = new Storyboard();
var timeline = new DoubleAnimationUsingKeyFrames();
Storyboard.SetTarget(timeline, rotateTransform);
Storyboard.SetTargetProperty(timeline, new PropertyPath("(Angle)"));
var frame = new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(5), Value = 360, EasingFunction = new QuadraticEase() { EasingMode = EasingMode.EaseOut } };
timeline.KeyFrames.Add(frame);
board.Children.Add(timeline);
board.RepeatBehavior = RepeatBehavior.Forever;
board.Begin();
}
private async void Spinner_Loaded(object sender, RoutedEventArgs e)
{
PlayRotation();
}
}
}
Then when you want to use Spinner in another xaml, it's very simple:
Just add a line for it inside any Grid etc:
<include:Spinner/>
(of course you need to define include as something like:
xmlns:include="MyControls"
on top of your xaml)
I have a few internal Canvas xaml files which I want to load dynamically at runtime. For example, I want to display the Canvas in a page. However, I cannot seem to get it to work. I've tried using XamlReader, Application.LoadComponent, and using an XDocument; all to no avail. I cannot seem to find the best practice for this on-line either.
The Canvases are stored like this: MyApp/Resources/Logos/Logo1.xaml. I'm not sure if Logo1.xaml should have a build action of "Component" or "Resource". In any case, using the URI of "MyApp;components/Resources/Logos/Logo1.xaml" seems to be correct, but Application.LoadComponent gets an XamlParseException at Line 0 Position 0.
Here's a pseudo-example of Logo1.xaml:
<Canvas
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="286.233" Height="143.425">
<Canvas>
<Path />
<Path />
<Path />
<Path />
</Canvas>
</Canvas>
The data for the path elements has been omitted for brevity's sake.
Any ideas?
I got this to work using build action "Resource" and the XamlLoader with a ContentControl:
var resourceName = string.Format("MyApp;component/Resources/Logos/{0}.xaml", logoName);
var uri = new Uri(resourceName, UriKind.Relative);
var streamResourceInfo = Application.GetResourceStream(uri);
string xaml = null;
using (var resourceStream = streamResourceInfo.Stream)
{
using (var streamReader = new StreamReader(resourceStream))
{
xaml = streamReader.ReadToEnd();
}
}
Canvas canvas = XamlReader.Load(xaml) as Canvas;
this.contentControl.Content = canvas;
The accepted answer is not intuitive to me, but may suit some people.
I generally feel more comfortable with System.IO.File.WriteAllText and System.IO.File.ReadAllText. I borrowed a code piece from MSDN. For a test, just create a new Canvas at runtime:
Canvas newCanvas = new Canvas()
Then, just write it out, with File.WriteAllText, simple too, avoiding all the URI stuff, which as a beginner I find confusing. Lastly, just read it back in as above. Done. This proves you can simply just read in some valid code for a canvas from a text file, and it can be loaded dynamically.
private void Button2_Click(object sender, RoutedEventArgs e)
{
Canvas newCanvas = new Canvas();
newCanvas.Name = "newCanvas";
string savedCanvas = XamlWriter.Save(newCanvas);
File.WriteAllText("savedCanvas.txt", savedCanvas);
savedCanvas = File.ReadAllText("savedCanvas.txt");
// Load the canvas
StringReader stringReader2 = new StringReader(savedCanvas);
XmlReader xmlReader2 = XmlReader.Create(stringReader2);
Canvas newCreatedCanvas = (Canvas)XamlReader.Load(xmlReader2);
this.Content = newCreatedCanvas;
}
The ideas are from MSDN as below:
XamlReader.Load Method (XmlReader)
.NET Framework 4
Reads the XAML input in the specified XmlReader and returns an object that is the root of the corresponding object tree.
Namespace: System.Windows.Markup
Assembly: PresentationFramework (in PresentationFramework.dll)