I am working on an application that captures real time pen strokes on a canvas using Wacom Bamboo Slate. The application is being developed for UWP platform using C#. After drawing on the canvas, save feature is to be implemented. I am using this for my reference. Below is the code and error message:
private async void BtnSave_Click(object sender, RoutedEventArgs e)
{
StorageFolder storageFolder = KnownFolders.SavedPictures;
var file = await storageFolder.CreateFileAsync("sample.jpg", CreationCollisionOption.ReplaceExisting);
CanvasDevice device = CanvasDevice.GetSharedDevice();
CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96);
using (var ds = renderTarget.CreateDrawingSession())
{
ds.Clear(Colors.White);
ds.DrawInk(inkCanvas.InkPresenter.StrokeContainer.GetStrokes());
}
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Jpeg, 1f);
}
}
CS1061 'InkCanvas' does not contain a definition for InkPresenter and no accessible extension method InkPresenter accepting a first argument of type InkCanvas could be found (are you missing a using directive or an assembly reference?)
Have you considered:
RenderTargetBitmap rtb = new RenderTargetBitmap((int)inkCanvas.Width, (int)inkCanvas.Height, 96d, 96d, PixelFormats.Default);
rtb.Render(inkCanvas);
After which you can then:
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
encoder.Save(fileStream);
The sample referred above can be found here.
The sample use CanvasDevice from the Microsoft.Graphics.Canvas namespace part of the package Win2D.UWP (version 1.6.0) from Microsoft. The UWP project sample targets build 10240 (minimum 10240) of Windows 10.
The package Win2D.UWP can be installed
using the menu "Project > Manage Nuget Packages", or
by selecting the context menu "References" in the UWP project of "Solution Explorer".
Select "Installed" and uninstall the current 2d graphics rendering package, if any.
Select "Browse", look for Win2D.UWP and install the one from Microsoft.
Please note that the latest version of Win2D.UWP updated 5/17/2018 version 1.23.0 requires target platform to be 17134.
For example, "Error List" might show the following error message after a build with version 1.23 of Win2D.UWP and target version set to 10240 in the UWP project properties:
This version of Win2D requires Windows SDK >= 10.0.17134.0, but TargetPlatformVersion is 10.0.10240.0.
Target version can be changed in the UWP project properties
select menu "Project > projectname Properties", or
by selecting the context menu "Properties" from the UWP project in "Solution Explorer".
PS: Add the following after InitializeComponent(); in MainPage.xaml.cs to enable drawing with a selection of input device types:
MyInkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Touch;
Related
I am following a tutorial on how to browse images on the phone with Xamarin Forms.
In the MainPage.xaml I have:
<Button Text="Select a picture"
Clicked="SelectImageButton_Clicked"/>
<Image x:Name="selectedImage"/>
</StackLayout>
In the MainPage.xaml.cs, is the following code for the Click event handler:
private async void SelectImageButton_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("Error", "This is not supported on your device", "OK");
return;
}
var mediaOptions = new PickMediaOptions()
{
PhotoSize = PhotoSize.Medium
};
var selectedImageFile = await CrossMedia.Current.PickPhotoAsync(mediaOptions);
if (selectedImageFile == null)
{
await DisplayAlert("Error", "The picture is null", "OK");
return;
}
selectedImage.Source = ImageSource.FromStream(() => selectedImageFile.GetStream());
}
Building the solution works, but as soon as I press the button in the emulator, I get an error.
So, I have set the linker (Droid Properties > Android Options > Linking) to Sdk Assemblies Only.
Then i get the following error when trying to build the solution:
Java.Interop.Tools.Diagnostics.XamarinAndroidException: error XA2006: Could not resolve reference to 'Xamarin.Essentials.Permissions/BasePlatformPermission' (defined in assembly 'Plugin.Media, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null') with scope 'Xamarin.Essentials, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. When the scope is different from the defining assembly, it usually means that the type is forwarded.
I have created a new project, updated the Xamarin.Forms NuGet Package to version 4.6.0.726,
updated the Xamarin.Essentials version to 1.5.3.1 and then installed the xam.plugin.media package, version 5.0.1
When trying to find similar issues with solutions, I found that there might be a reference to Essentials that is not pointing to the correct version and that I should change that in the Android project within the solution. However, since I am pretty new to Xamarin and Android development, I would not know where to find these references.
Am I on the right track towards a solution, and if yes: what steps do I need to take to resolve this?
If (!rightTrack)
{
return solution;
}
Many thanks in advance for your input!
When I test your code with the same version of Xamarin.Forms, Xamarin.Essentials, xam.plugin.media, I reproduce the error BasePlatformPermission.
You could use the older version 4.0.1.5 of xam.plugin.media. The error would fix.
Im new in xamarin studio and im trying to create a cocosproject following the official guide, but this document is not very clear and my project have so many errors.
https://developer.xamarin.com/guides/xamarin-forms/advanced/cocossharp/#nuget
I've created a xamarin.form with IOS, android and PCL as guide say
I've added the cocosSharp packages to IOS and Android projects
BUT
if i don't add the cocosSharp package to PCL target, the cocos Classes cant be found by the code
And if I try to add the cocosSharp packages to PCL, console show this
Could not install package 'CocosSharp 1.7.1'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile259', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
i tried to change the targetFramework but this don't help me
if someone work with cocosSharp and xamarin studio V6, please how can i solve this ?
Or how can i add the add in of cocosSharp in Galery like in previous versions of xamarin ?
This is the code in a ContentPage, Cocos Classes can't be found
public class MyPage : ContentPage
{
public MyPage()
{
Content = new StackLayout
{
Children = {
new Label { Text = "Hello ContentPage" }
}
};
}
void CreateTopHalf(Grid grid)
{
// This hosts our game view.
var gameView = new CocosSharpView()
{
// Notice it has the same properties as other XamarinForms Views
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
// This gets called after CocosSharp starts up:
ViewCreated = HandleViewCreated
};
// We'll add it to the top half (row 0)
grid.Children.Add(gameView, 0, 0);
}
void HandleViewCreated(object sender, EventArgs e)
{
var gameView = sender as CCGameView;
if (gameView != null)
{
// This sets the game "world" resolution to 100x100:
gameView.DesignResolution = new CCSizeI(100, 100);
// GameScene is the root of the CocosSharp rendering hierarchy:
gameScene = new GameScene(gameView);
// Starts CocosSharp:
gameView.RunWithScene(gameScene);
}
}
}
just figured this out myself. It's true that there's no matching build for Profile 259. Try 151 instead:
Right click the PCL project in your solution explorer
Click 'Options'
Click 'General' on the left hand side.
Change the Current Profile to "PCL 4.6 - Profile151"
Click 'OK'.
Now you'll need to refresh the Nuget Packages so that Xamarin Forms can redownload the right profile. Afterward you can successfully add CocosSharp.Forms.
I want to create simple toast notification to action center in windows 10 from this example. But I got problem on Step 2:
using Windows.UI.Notifications;
It`s missing. But I have spent a lot of time to find it and got no result. I really have no idea where I can find or at least download it.
What I tried:
After long search I found Windows.UI.dll in C:\Windows\System32 but when I try to add it as reference into project I got this error. Even after I tried to copy it and made this fully accessible nothing changed
I tried to reinstall .Net (I`m using 4.5.2)
Installed Windows 10 SDK
Tried to import with global
Added
<PropertyGroup>
<TargetPlatformVersion>10.0</TargetPlatformVersion>
</PropertyGroup>
Added System.Runtime.dll reference
Example code which probably is useless for you:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Uwp.Notifications;
using Microsoft.QueryStringDotNET;
using Windows.UI.Notifications;
namespace MessagerClient.Notifications {
class DefaultWindowsNotification {
public static void notificationTest() {
string title = "Andrew sent you a picture";
string content = "Check this out, Happy Canyon in Utah!";
string image = "http://blogs.msdn.com/something.jpg";
string logo = "ms-appdata:///local/Andrew.jpg";
ToastVisual visual = new ToastVisual() {
BindingGeneric = new ToastBindingGeneric() {
Children =
{
new AdaptiveText()
{
Text = title
},
new AdaptiveText()
{
Text = content
},
new AdaptiveImage()
{
Source = image
}
},
AppLogoOverride = new ToastGenericAppLogo() {
Source = logo,
HintCrop = ToastGenericAppLogoCrop.Circle
}
}
};
Console.WriteLine("NOTIFICATION");
//Can`t use because of Windows.UI library
ToastNotificationManager.CreateToastNotifier().Show(visual);
}
}
}
You have to fight Visual Studio pretty hard to use these UWP contracts in a Winforms app. You got off on the wrong foot right away with the wrong TargetPlatformVersion, pretty hard to recover from that. Full steps to take:
Edit the .csproj file with a text editor, Notepad will do. Insert this:
<PropertyGroup>
<TargetPlatformVersion>10.0.10586</TargetPlatformVersion>
</PropertyGroup>
Which assumes you have the 10586 SDK version installed on your machine. Current right now, these versions change quickly. Double-check by looking in the C:\Program Files (x86)\Windows Kits\10\Include with Explorer, you see the installed versions listed in that directory.
Open the Winforms project, use Project > Add Reference > Windows tab > tick the Windows.Data and the Windows.UI contract. Add Reference again and use the Browse tab to select System.Runtime. I picked the one in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\ .NETFramework\v4.6.1\Facades. This reference displays with a warning icon, not sure what it is trying to say but it doesn't appear to have any side-effects.
Test it by dropping a button on the form, double-click to add the Click event handler. The most basic code:
using Windows.UI.Notifications;
...
private void button1_Click(object sender, EventArgs e) {
var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
var text = xml.GetElementsByTagName("text");
text[0].AppendChild(xml.CreateTextNode("Hello world"));
var toast = new ToastNotification(xml);
ToastNotificationManager.CreateToastNotifier("anythinggoeshere").Show(toast);
}
Embellish by using a different ToastTemplateType to add an image or more lines of text. Do keep in mind that your program can only work on a Win10 machine.
If anyone should happen to stumble on this, see this similar but newer post -
Toast Notifications in Win Forms .NET 4.5
Read Stepan Hakobyan's comment at the bottom.
Essentially, I'm seeing the same thing. This code runs, I can step through it line by line with no exceptions but the toast notification is never shown within a Form app.
I'm trying to use the OxyPlot.Xamarin.Forms package in my shared Xamarin.Forms project. I added the OxyPlot packages with the NuGet package manager in both the portable and the platform specific (Android) projects like descriped at:
http://docs.oxyplot.org/en/latest/getting-started/hello-xamarin-forms.html
Then I initialized the OxyPlot renderers in the Android project. Now, when I try to start the App the Resource.Designer.cs file is generated, but I get hundreds of errors like so:
Error CS0117 'Resource.Attribute' does not contain a definition for 'mediaRouteSettingsDrawable' OxyPlotShared.Droid \OxyPlotShared\OxyPlotShared.Droid\Resources\Resource.Designer.cs
I use Xamarin.Forms v2.2.0.31 and all OxyPlot packages in version 1.0.0-unstable1983.
Am I missing something?
Note that there are 2 different project templates: Portable and Shared. In your post you mention both of them, so be clear about which one you're using. The specific example you're following is for a Portable project template. After adding the OxyPlot Nuget Package, I had to manually add OxyPlot and OxyPlot.Xamarin.Forms to the References of the Portable one. After that, it worked just fine. I'm using Xamarin.Forms 2.0.0.6482 and OxyPlot 1.0.0-unstable1983.
I added the PlotView using code:
App.cs:
public App()
{
PlotModel plotModel = new PlotModel { PlotAreaBackground = OxyColors.LightYellow };
plotModel.Series.Add(new FunctionSeries(Math.Sin, -10, 10, 0.1, "sin(x)"));
// The root page of your application
MainPage = new ContentPage {
Content = new PlotView {
VerticalOptions = LayoutOptions.Fill,
HorizontalOptions = LayoutOptions.Fill,
Model = plotModel
}
};
}
I want to extract exif data from jpg images. ExifLib seemed like a good choice to simplify this chore, and so I installed it via NuGet.
I then tried to get started using the sample code from here (commenting out the MessageBox code for now):
using (ExifReader reader = new ExifReader(#"C:\temp\testImage.jpg"))
{
// Extract the tag data using the ExifTags enumeration
DateTime datePictureTaken;
if (reader.GetTagValue<DateTime>(ExifTags.DateTimeDigitized, out datePictureTaken))
{
// Do whatever is required with the extracted information
//System.Windows.MessageBox.Show(this, string.Format("The picture was taken on {0}",
// datePictureTaken), "Image information"); //, MessageBoxButtons.OK);
}
}
but get an error:
The best overloaded method match for 'ExifLib.ExifReader.ExifReader(System.IO.Stream)' has some invalid arguments
and
Argument 1: cannot convert from 'string' to 'System.IO.Stream'
both on this line:
using (ExifReader reader = new ExifReader(#"C:\temp\testImage.jpg"))
Is this fixable, or is ExifLib not usable from a WPF / XAML app?
If ExifLib is not a viable solution for a WPF / XAML app, what alternatives exist?
Update:
With this code, from Simon McKenzie's answer:
private void btnLoadNewPhotoset_Click(object sender, RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = store.OpenFile("testImage.jpg", FileMode.Open))
using (var reader = new ExifReader(stream))
{
// ...
}
}
I still get an error:
The type or namespace name 'IsolatedStorage' does not exist in the namespace 'System.IO' (are you missing an assembly reference?)
This is a Windows Store (C#) app created in Visual Studio 2013. The project's properties shows that it targets Windows 8.1, and Configuration Manager shows configuration == debug, platform = x64)
My project's displayed References are:
.NET for Windows Store apps
Bing.Maps.Xaml
ExifLib
Microsoft Visual C++ Runtime Package
Windows 8.1
What am I missing?
Update 2:
When I look in Reference Manager at Assemblies.Framework, it says, "All of the Framework assembles are already referenced..." I assume mscorlib.dll is supposed to be one of these (it doesn't list them)?
I searched my hard drive for "mscorlib.dll" and I've got a million of them, all different sizes and dates. Which one should I try to add as a reference? I've got everything from one in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5 dated 7/9/2012 with file size of 2,564,528 to one in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5.1 to...you name it.
Thinking "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5.1" seemed the best bet, I tried to reference it via the Browse button, but when I did, I got scolded with:
In the interests of full disclosure, in Reference Manager for Windows 8.1, it says, "The Windows 8.1. SDK is already referenced."
For Windows 8.1.Extensions, it shows me:
Microsoft Visual C++ 2013 Runtime Package for Windows 12.0 (unchecked)
Microsoft Visual C++ 2013 Runtime Package 11.0 (checked)
Since this seems to be the cause of one of the warnings, I reversed their checkedness (checked 2013,
unchecked the other).
I also checked:
Behaviors SDK (XAML) 12.0
SQLite for Windows Runtime 3.8.6 (because I will eventually be using SQLite in this project)
Update 3:
I just found this: "Isolated storage is not available for Windows Store apps. Instead, use the application data classes in the Windows.Storage namespaces included in the Windows Runtime API to store local data and files." here.
Update 4:
I'm waiting for Simon's example, but I'm thinking it might be something like this:
using Windows.Storage;
using ExifLib;
. . .
private async void btnOpenImgFiles_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
IReadOnlyList<StorageFile> files = await openPicker.PickMultipleFilesAsync();
for (int i = 0; i < files.Count; i++)
{
using (var randomAccessStream = await files[i].OpenAsync(FileAccessMode.Read))
using (var stream = randomAccessStream.AsStream())
using (var exfrdr = new ExifReader(stream))
{
// ...exfrdr
}
}
}
this has nothing to do with WPF
try something like this
using (ExifReader reader = new ExifReader(File.Open(#"C:\temp\testImage.jpg",FileMode.Open)))
The string constructor is not available in Windows Phone/Windows Store apps because they aren't allowed direct filesystem access. You will instead need to pass in a stream containing your image. Here's an example using a FileOpenPicker. Note the use of AsStream(...) to convert the IRandomAccessStream into a Stream for use with an ExifReader.
using System;
using System.IO;
using Windows.Storage;
using Windows.Storage.Pickers;
// ...
var picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".jpg");
var file = await picker.PickSingleFileAsync();
using (var randomAccessStream = await file.OpenAsync(FileAccessMode.Read))
{
using (var stream = randomAccessStream.AsStream())
{
using (var reader = new ExifReader(stream))
{
string model;
if (reader.GetTagValue(ExifTags.Model, out model))
{
var dialog = new MessageDialog(model, "Camera Model");
dialog.ShowAsync();
}
}
}
}