What I'm trying to do in a UWP app with Win2D:
User pressed a button to add an image and picks their file.
That file gets loaded as a resource for a Canvas Control.
The image then gets rendered to the current drawing session
When the button is clicked:
private async void btnAddPicture_Click(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
overlayPictureFile = await picker.PickSingleFileAsync();
if (overlayPictureFile == null)
{
txbNotification.Text = "File Picking cancelled";
return;
}
else
{
txbNotification.Text = "Picture Loaded";
}
using (IRandomAccessStream stream = await overlayPictureFile.OpenAsync(FileAccessMode.Read))
{
var device = new CanvasDevice();
createdBitmap = await CanvasBitmap.LoadAsync(device, stream);
}
}
In the drawing function:
void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
if (createdBitmap != null)
{
args.DrawingSession.DrawImage(createdBitmap, Drawing.FindDefaultRect());
}
drawingCanvas.Invalidate();
}
Everything will compile but the moment I press the button to add an image it breaks here.
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
I'm already loading some image in this, but those are all part of the program and are created before the canvas is created with these. Not sure how to do that with ones the user picks.
private void drawingCanvas_CreateResources(CanvasControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args)
{
args.TrackAsyncAction(CreateResourcesAsync(sender).AsAsyncAction());
}
private async Task CreateResourcesAsync(CanvasControl sender)
{
logo = await CanvasBitmap.LoadAsync(sender, new Uri("ms-appx:///Assets/Pictures/Logo_BlackBorders.png"));
}
Update:
Where I currently am drawing things. This is the canvas I'm trying to add the image to.
void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
//Drawing a bunch of stuff
}
private void drawingCanvas_CreateResources(CanvasControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args)
{
args.TrackAsyncAction(CreateResourcesAsync(sender).AsAsyncAction());
}
private async Task CreateResourcesAsync(CanvasControl sender)
{
logo = await CanvasBitmap.LoadAsync(sender, new Uri("ms-appx:///Assets/Pictures/Logo.png"));
}
Load an Image to a Canvas Control from a File Picker
For your scenario, you could get CanvasDrawingSession with CreateDrawingSession method. And then use this drawingsession to draw picked image to current CanvasControl.
For example.
private async void btnAddPicture_Click(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
var overlayPictureFile = await picker.PickSingleFileAsync();
if (overlayPictureFile == null)
{
return;
}
else
{
}
using (IRandomAccessStream stream = await overlayPictureFile.OpenAsync(FileAccessMode.Read))
{
//get canvascontrol's Device property.
CanvasDevice device = drawingCanvas.Device;
createdBitmap = await CanvasBitmap.LoadAsync(device, stream);
//use device property to make renderer
var renderer = new CanvasRenderTarget(device,
createdBitmap.SizeInPixels.Width,
createdBitmap.SizeInPixels.Height, createdBitmap.Dpi);
//make ds with above renderer.
using (var ds = renderer.CreateDrawingSession())
{
ds.DrawImage(createdBitmap, 0, 0);
}
}
}
Related
I have a Xamarin.Forms application that supports only UWP. I cannot find a way to print a pdf document. Whatever I have seen on the web, for some reason doesn't work for me. E.g. I tried
https://www.syncfusion.com/kb/8767/how-to-print-pdf-documents-in-xamarin-forms-platform
It lets me print, but the preview in the print dialog never shows up, and the progress indicator just keeps rotating forever.
I also tried http://zawayasoft.com/2018/03/13/uwp-print-pdf-files-silently-without-print-dialog/
This gives me errors that I cannot fix.
So I wonder if somebody can suggest something else that would actually work. Maybe something newer than what I have tried (I use VS 2017). Printing without the printing dialog would be preferable.
Thank you in advance.
I used a very dirty hack to do that!
What I had to do was to try to print the image version of the pdf (I did the conversion in backend) and then used the following DependencyInjection:
Inside my Print class in UWP project:
class Print : IPrint
{
void IPrint.Print(byte[] content)
{
Print_UWP printing = new Print_UWP();
printing.PrintUWpAsync(content);
}
}
and the class responsible for printing in uwp:
public class Print_UWP
{
PrintManager printmgr = PrintManager.GetForCurrentView();
PrintDocument PrintDoc = null;
PrintDocument printDoc;
PrintTask Task = null;
Windows.UI.Xaml.Controls.Image ViewToPrint = new Windows.UI.Xaml.Controls.Image();
public Print_UWP()
{
printmgr.PrintTaskRequested += Printmgr_PrintTaskRequested;
}
public async void PrintUWpAsync(byte[] imageData)
{
int i = 0;
while (i < 5)
{
try
{
BitmapImage biSource = new BitmapImage();
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(imageData.AsBuffer());
stream.Seek(0);
await biSource.SetSourceAsync(stream);
}
ViewToPrint.Source = biSource;
if (PrintDoc != null)
{
printDoc.GetPreviewPage -= PrintDoc_GetPreviewPage;
printDoc.Paginate -= PrintDoc_Paginate;
printDoc.AddPages -= PrintDoc_AddPages;
}
this.printDoc = new PrintDocument();
try
{
printDoc.GetPreviewPage += PrintDoc_GetPreviewPage;
printDoc.Paginate += PrintDoc_Paginate;
printDoc.AddPages += PrintDoc_AddPages;
bool showprint = await PrintManager.ShowPrintUIAsync();
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
// printmgr = null;
// printDoc = null;
// Task = null;
PrintDoc = null;
GC.Collect();
printmgr.PrintTaskRequested -= Printmgr_PrintTaskRequested;
break;
}
catch (Exception e)
{
i++;
}
}
}
private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
var deff = args.Request.GetDeferral();
Task = args.Request.CreatePrintTask("Invoice", OnPrintTaskSourceRequested);
deff.Complete();
}
async void OnPrintTaskSourceRequested(PrintTaskSourceRequestedArgs args)
{
var def = args.GetDeferral();
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
args.SetSource(printDoc.DocumentSource);
});
def.Complete();
}
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(ViewToPrint);
printDoc.AddPagesComplete();
}
private void PrintDoc_Paginate(object sender, PaginateEventArgs e)
{
PrintTaskOptions opt = Task.Options;
printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
}
private void PrintDoc_GetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
printDoc.SetPreviewPage(e.PageNumber, ViewToPrint);
}
}
Please note that this is not a perfect solution and sometimes it crashes without actually being able to trace the exception (which is really strange) so I am sure there must be better answers even though it does the job.
I have managed to pick an image from the phones library and display it. this is the code. Question is how do i Insert this image into my Sqlite database of contacts and retrieve it and display it again after getting the image? Here is my code. A detailed step by step instruction would be appreciated from here.
namespace Mobile_Life.Pages
{
public sealed partial class NextOFKin_Update_Delete : Page
{
int Selected_ContactId = 0;
DatabaseHelperClass Db_Helper = new DatabaseHelperClass();
Contacts currentcontact = new Contacts();
CoreApplicationView view;
public NextOFKin_Update_Delete()
{
this.InitializeComponent();
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
view = CoreApplication.GetCurrentView();
}
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if (Frame.CanGoBack)
{
e.Handled = true;
Frame.GoBack();
}
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await StatusBar.GetForCurrentView().ShowAsync();
Selected_ContactId = int.Parse(e.Parameter.ToString());
currentcontact = Db_Helper.ReadContact(Selected_ContactId);//Read selected DB contact
namestxt.Text = currentcontact.Name;//get contact Name
relationtxt.Text = currentcontact.Relation;//get contact relation
phonetxt.Text = currentcontact.PhoneNumber;//get contact PhoneNumber
}
private void Update_click(object sender, RoutedEventArgs e)
{
currentcontact.Name = namestxt.Text;
currentcontact.Relation = relationtxt.Text;
currentcontact.PhoneNumber = phonetxt.Text;
Db_Helper.UpdateContact(currentcontact);//Update selected DB contact Id
Frame.Navigate(typeof(NextOfKin));
}
private void Delete_click(object sender, RoutedEventArgs e)
{
Db_Helper.DeleteContact(Selected_ContactId);//Delete selected DB contact Id.
Frame.Navigate(typeof(NextOfKin));
}
private void profile_img(object sender, TappedRoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
}
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(FileAccessMode.Read);
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
profile.ImageSource = bitmapImage;
}
}
}
The best way would be NOT to store the image in SQLite. Just copy it to your ApplicationData.Current.LocalFolder and save the path.
If you really want to store the BitmapImage in SQLite, just convert it to byte array: Convert a bitmapimage to byte[] array for storage in sqlite database
I have 2 list views and I'm trying to drag an item from one to the other.
The typeof item is a storagefile.
private async void ListA_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
List<IStorageItem> files = new List<IStorageItem>();
StorageFile file = e.Items;
files.Add(file);
e.Data.SetStorageItems(files);
}
private void ListC_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
}
private async void ListC_Drop(object sender, DragEventArgs e)
{
//if (e.DataView.Contains(StandardDataFormats.StorageItems))
//{
// var items = await e.DataView.GetStorageItemsAsync();
// if (items.Count > 0)
// {
// var storageFile = items[0] as StorageFile;
// ListC.Items.Add(storageFile);
// }
// }
}
I've tried everything I can think of to drop the storage file into the other listview and show the display name... All I've been able to display are types and stuff.
Can anyone help me?
I've solved it after hours or trying.
private async void ListA_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
//f.MessageBox(e.Items.First().GetType().ToString());
try
{
List<IStorageItem> files = new List<IStorageItem>();
StorageFile file = e.Items.First() as StorageFile;
files.Add(file);
e.Data.SetStorageItems(files);
//e.Data.SetData(StandardDataFormats.Text, e.Items.);
}catch(Exception ex)
{
f.MessageBox(ex.Message);
}
}
private async void ListC_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
//IReadOnlyList<IStorageItem> files = await e.DataView.GetStorageItemsAsync();
}
private async void ListC_Drop(object sender, DragEventArgs e)
{
try
{
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
if (items.Count > 0)
{
var storageFile = items[0] as StorageFile;
ListC.Items.Add(storageFile.Name);
}
}
}catch
{
f.MessageBox("nope");
}
I am trying to get my program to read a simple text file, but after 12+ hours of reading his example, I am getting a little frustrated. The PickSingleFileAsync for Windows app is so easy to understand, but cannot be used for WP8 :)
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn614994.aspx
Edit: Ok, my main problem is this: Inside the ContinuationManager, after I choose a file my fileOpenPickerPage is null, and I do not know why.
I have downloaded the code, and implemented the ContinuationManager class in my program. I have the SuspensionManager help class in my code.
Here is my code:
ContinuationManager (As the example)
SuspensionManager (Generated by Visual Basic)
App.xaml.cs file: The Frame is the problem here I think.
public sealed partial class App : Application
{
#if WINDOWS_PHONE_APP
public ContinuationManager continuationManager { get; private set; }
#endif
Some code..............................
#if WINDOWS_PHONE_APP
protected override async void OnActivated(IActivatedEventArgs e)
{
string test = Convert.ToString (e);
base.OnActivated(e);
continuationManager = new ContinuationManager();
Frame rootFrame = CreateRootFrame();
await RestoreStatusAsync(e.PreviousExecutionState);
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage));
}
var continuationEventArgs = e as IContinuationActivatedEventArgs;
if (continuationEventArgs != null)
{
Frame scenarioFrame = MainPage.Current.FindName("ScenarioFrame") as Frame;
if (scenarioFrame != null)
{
MessageDialog msg2 = new MessageDialog("scenarioFrame is\n" + Convert.ToString(rootFrame.Content));
await msg2.ShowAsync();
// Call ContinuationManager to handle continuation activation
continuationManager.Continue(continuationEventArgs, scenarioFrame);
}
}
Window.Current.Activate();
}
#endif
LoadSavePage (Page where I want to push a button and read/load a file.
public sealed partial class LoadSavePage : Page, IFileOpenPickerContinuable
{
.......Some Code............
private void LoadWeapons_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
openPicker.FileTypeFilter.Add(".txt");
openPicker.PickSingleFileAndContinue();
}
Replace your code with below :
Add this two lines in LoadWeapons_Click after openPicker.PickSingleFileAndContinue();.
Add using Windows.ApplicationModel.Core; namespace to access CoreApplicationView.
CoreApplicationView view = CoreApplication.GetCurrentView();
view.Activated += viewActivated;
Edit :
private void LoadWeapons_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
openPicker.FileTypeFilter.Add(".txt");
openPicker.PickSingleFileAndContinue();
CoreApplicationView view = CoreApplication.GetCurrentView();
view.Activated += viewActivated;
}
And finally copy below handler in your code.
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
try
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
if (args.Files.Count > 0)
{
// Application now has read/write access to the picked file(s)
foreach (StorageFile file in args.Files)
{
// Launch file.
bool filelaunch = await Windows.System.Launcher.LaunchFileAsync(file);
}
}
}
}
catch (Exception ex)
{ }
}
I am trying to import music files from your pc to make your own playlist.
code below:
public async void Button_Click(object sender, RoutedEventArgs e) // Pick directory
{
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.FileTypeFilter.Add(".wmv");
openPicker.FileTypeFilter.Add(".mp4");
openPicker.FileTypeFilter.Add(".wma");
openPicker.FileTypeFilter.Add(".mp3");
var file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
// media is a MediaElement defined in XAML
if (null != file)
{
media.SetSource(stream, file.ContentType);
media.Play();
}
}
private async void Button_Click_1(object sender, RoutedEventArgs e) //Import file
{
this.Frame.Navigate(typeof(importedfile));
importedfile import = new importedfile(); // The imported file goes to that page.
//What do I do to get the imported file into a new grid (Picture below
}
For example: I Import a song and I hit the import button it will navigate me to the importedfile page but what do I do next?.