GWT 2.5 Canvas toDataURL() works in MouseUp handler but not TouchEnd Handler - events

I have implemented a digital signature widget using the GWT 2.5 Canvas which works great with mouse events. Unfortunately it fails miserably for touch events and I have no idea why. On a touch screen the signature is drawn but canvas.toDataURL() alway return nothing ("data:," actually). Code snippets are:
_canvas.addMouseMoveHandler(new MouseMoveHandler() {
public void onMouseMove(MouseMoveEvent event) {
int thisX = event.getRelativeX(_canvas.getElement());
int thisY = event.getRelativeY(_canvas.getElement());
if (_lastX >= 0 && _lastY >= 0) {
_exists = true;
_context.moveTo(_lastX, _lastY);
_context.lineTo(thisX, thisY);
_context.stroke();
}
_lastX = thisX;
_lastY = thisY;
}
});
_canvas.addMouseUpHandler(new MouseUpHandler() {
public void onMouseUp(MouseUpEvent event) {
_lastX = -1;
_lastY = -1;
_drawing = false;
if (_exists) _handler.sigChanged(_canvas.toDataUrl());
}
});
_canvas.addTouchMoveHandler(new TouchMoveHandler() {
public void onTouchMove(TouchMoveEvent event) {
if (event.getTouches().length() > 0) {
Touch touch = event.getTouches().get(0);
int thisX = touch.getRelativeX(_canvas.getElement());
int thisY = touch.getRelativeY(_canvas.getElement());
if (_lastX >= 0 && _lastY >= 0) {
_context.moveTo(_lastX, _lastY);
_context.lineTo(thisX, thisY);
_context.stroke();
//_handler.sigChanged(_canvas.toDataUrl());
}
_lastX = thisX;
_lastY = thisY;
}
event.preventDefault();
event.stopPropagation();
}
});
_canvas.addTouchEndHandler(new TouchEndHandler() {
public void onTouchEnd(TouchEndEvent event) {
_handler.sigChanged(_canvas.toDataUrl());
com.google.gwt.user.client.Window.alert("onTouchEnd1: " + _canvas.toDataUrl());
}
event.preventDefault();
});
Again, toDataURL() works fine for the mouse events but always return nothing in the touch events, even if you call it from the touch move handler. Any help or suggestions would be greatly appreciated.

I borrowed a friends android phone that is running a newer version (4.1 vs 2.3) and it works. I don't understand it but I assume it's a bug with GWT 2.5 and I'm moving on.
James

Related

how to use GetAxisRaw with 2d movement (beginner unity)

I am making a platformer game where you have to dodge spikes, and I tried to use the transform.position method, but it gave too many bugs. With rigidbodies(rb.addforce), it has acceleration, and I saw somewhere that you could use getaxisraw to do it. Is there any way that I could add this to my current script without deviating too much (still being able to use wasd and arrow keys)?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerscript : MonoBehaviour
{
public float movespeed = 0.01f;
public Rigidbody2D rb;
public bool isgrounded = true;
public float jumpheight = 500f;
public float level = 1;
// Start is called before the first frame update
void Start()
{
rb = this.gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey(KeyCode.A) || (Input.GetKey(KeyCode.LeftArrow)))
{
rb.AddForce(-Vector2.right * movespeed);
}
if (Input.GetKey(KeyCode.W) && isgrounded || (Input.GetKey(KeyCode.UpArrow) && isgrounded))
{
rb.AddForce(transform.up * jumpheight);
isgrounded = false;
}
if (Input.GetKey(KeyCode.D)||(Input.GetKey(KeyCode.RightArrow)))
{
rb.AddForce(Vector2.right * movespeed);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "enemy")
{
Debug.Log("hio");
if (level == 1)
{
Debug.Log("resetpos");
transform.position = new Vector3((float)-11.343, (float)-0.49, 0);
}
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag == "ground")
{
isgrounded = true;
}
}
}
From https://docs.unity3d.com/ScriptReference/Input.GetAxisRaw.html, I think that Input.GetAxisRaw("Horizontal") will return -1 if the user presses in left or a, 0 if the user is not pressing left or right or a or d, and 1 if the user presses right or d. Similarly, this also occurs for Input.GetAxisRaw("Vertical"). I think it will return -1 if the user wants to go down, 0 if the user is not pressing up or down, and 1 if the user wants to go up.
In FixedUpdate(), you can get Input.GetAxisRaw("Horizontal") to get whether they want to move right or left, and Input.GetAxisRaw("Vertical") to get whether they want to move down or up. Then, you can handle it by moving the character appropriately.
For example, you can do this:
void FixedUpdate()
{
if (Input.GetAxisRaw("Horizontal") == -1)
{
// Code to move left
}
else if (Input.GetAxisRaw("Horizontal") == 1) {
// Code to move right
}
if (Input.GetAxisRaw("Vertical") == -1)
{
// Code to move down or squat
}
else if (Input.GetAxisRaw("Vertical") == 1)
{
// Code to move up or jump
}
}
Please excuse me if I made any C# syntax errors.

Xamarin Forms Cross and Camera control

For my studying project, I need to realize an application that has a CameraView or a CameraPage, with a special design. However, I’m not able to figure out how to realize it.
I found a lot of information, to be honest, but they are either obsolete or incomplete, so, I would like to make a point about it, through this thread!
How to implement a Camera?
Well, two solutions can be considered based on what I read.
Camera Page
Let’s say that it’s the first “official” solution. It’s proposed by Xamarin itself, with the Customizing a ContentPage tutorial/documentation. It explains you, through a web page how to implement the camera service with a cross-platform solution.
I then tried the UWP solution:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CameraPreviewProject.Sources.Pages.CameraPage">
<ContentPage.Content>
<AbsoluteLayout>
<Button Text="Click me !" AbsoluteLayout.LayoutBounds="0.5, 0.5, 0.1, 0.1" AbsoluteLayout.LayoutFlags="All" />
</AbsoluteLayout>
</ContentPage.Content>
</ContentPage>
Finally, the C# side gives us this:
public partial class CameraPage : ContentPage
{
public CameraPage()
{
InitializeComponent();
}
}
Then, we create a renderer in the UWP side :
using CameraPreviewProject.Sources.Pages;
using CameraPreviewProject.UWP.Sources.PageRenderers;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Devices.Enumeration;
using Windows.Devices.Sensors;
using Windows.Foundation;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.Storage.Streams;
using Windows.System.Display;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Xamarin.Forms.Platform.UWP;
[assembly: ExportRenderer(typeof(CameraPage), typeof(CameraPageRenderer))]
namespace CameraPreviewProject.UWP.Sources.PageRenderers
{
public class CameraPageRenderer : PageRenderer
{
private readonly DisplayInformation displayInformation = DisplayInformation.GetForCurrentView();
private readonly SimpleOrientationSensor orientationSensor = SimpleOrientationSensor.GetDefault();
private readonly DisplayRequest displayRequest = new DisplayRequest();
private SimpleOrientation deviceOrientation = SimpleOrientation.NotRotated;
private DisplayOrientations displayOrientation = DisplayOrientations.Portrait;
// Rotation metadata to apply to preview stream (https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx)
private static readonly Guid RotationKey = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1"); // (MF_MT_VIDEO_ROTATION)
private StorageFolder captureFolder = null;
private readonly SystemMediaTransportControls systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
private MediaCapture mediaCapture;
private CaptureElement captureElement;
private bool isInitialized;
private bool isPreviewing;
private bool externalCamera;
private bool mirroringPreview;
private Page page;
private AppBarButton takePhotoButton;
private Application app;
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
{
return;
}
try
{
app = Application.Current;
app.Suspending += OnAppSuspending;
app.Resuming += OnAppResuming;
SetupUserInterface();
SetupCamera();
this.Children.Add(page);
}
catch (Exception ex)
{
Debug.WriteLine(#" ERROR: ", ex.Message);
}
}
protected override Size ArrangeOverride(Size finalSize)
{
page.Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height));
return finalSize;
}
private void SetupUserInterface()
{
takePhotoButton = new AppBarButton
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Icon = new SymbolIcon(Symbol.Camera)
};
var commandBar = new CommandBar();
commandBar.PrimaryCommands.Add(takePhotoButton);
captureElement = new CaptureElement();
captureElement.Stretch = Stretch.UniformToFill;
var stackPanel = new StackPanel();
stackPanel.Children.Add(captureElement);
page = new Page();
page.BottomAppBar = commandBar;
page.Content = stackPanel;
page.Unloaded += OnPageUnloaded;
}
private async void SetupCamera()
{
await SetupUIAsync();
await InitializeCameraAsync();
}
#region Event Handlers
private async void OnSystemMediaControlsPropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
// Only handle event if the page is being displayed
if (args.Property == SystemMediaTransportControlsProperty.SoundLevel && page.Frame.CurrentSourcePageType == typeof(MainPage))
{
// Check if the app is being muted. If so, it's being minimized
// Otherwise if it is not initialized, it's being brought into focus
if (sender.SoundLevel == SoundLevel.Muted)
{
await CleanupCameraAsync();
}
else if (!isInitialized)
{
await InitializeCameraAsync();
}
}
});
}
private void OnOrientationSensorOrientationChanged(SimpleOrientationSensor sender, SimpleOrientationSensorOrientationChangedEventArgs args)
{
// Only update orientatino if the device is not parallel to the ground
if (args.Orientation != SimpleOrientation.Faceup && args.Orientation != SimpleOrientation.Facedown)
{
deviceOrientation = args.Orientation;
}
}
private async void OnDisplayInformationOrientationChanged(DisplayInformation sender, object args)
{
displayOrientation = sender.CurrentOrientation;
if (isPreviewing)
{
await SetPreviewRotationAsync();
}
}
private async void OnTakePhotoButtonClicked(object sender, RoutedEventArgs e)
{
await TakePhotoAsync();
}
/*async void OnHardwareCameraButtonPressed(object sender, CameraEventArgs e)
{
await TakePhotoAsync();
}*/
#endregion Event Handlers
#region Media Capture
private async Task InitializeCameraAsync()
{
if (mediaCapture == null)
{
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
var cameraDevice = devices.FirstOrDefault(c => c.EnclosureLocation != null && c.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
// Get any camera if there isn't one on the back panel
cameraDevice = cameraDevice ?? devices.FirstOrDefault();
if (cameraDevice == null)
{
Debug.WriteLine("No camera found");
return;
}
mediaCapture = new MediaCapture();
try
{
await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
VideoDeviceId = cameraDevice.Id,
AudioDeviceId = string.Empty,
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.Photo
});
isInitialized = true;
}
catch (UnauthorizedAccessException)
{
Debug.WriteLine("Camera access denied");
}
catch (Exception ex)
{
Debug.WriteLine("Exception initializing MediaCapture - {0}: {1}", cameraDevice.Id, ex.ToString());
}
if (isInitialized)
{
if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
{
externalCamera = true;
}
else
{
// Camera is on device
externalCamera = false;
// Mirror preview if camera is on front panel
mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
}
await StartPreviewAsync();
}
}
}
private async Task StartPreviewAsync()
{
// Prevent the device from sleeping while the preview is running
displayRequest.RequestActive();
// Setup preview source in UI and mirror if required
captureElement.Source = mediaCapture;
captureElement.FlowDirection = mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
// Start preview
await mediaCapture.StartPreviewAsync();
isPreviewing = true;
if (isPreviewing)
{
await SetPreviewRotationAsync();
}
}
private async Task StopPreviewAsync()
{
isPreviewing = false;
await mediaCapture.StopPreviewAsync();
// Use dispatcher because sometimes this method is called from non-UI threads
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// UI cleanup
captureElement.Source = null;
// Allow device screen to sleep now preview is stopped
displayRequest.RequestRelease();
});
}
private async Task SetPreviewRotationAsync()
{
// Only update the orientation if the camera is mounted on the device
if (externalCamera)
{
return;
}
// Derive the preview rotation
int rotation = ConvertDisplayOrientationToDegrees(displayOrientation);
// Invert if mirroring
if (mirroringPreview)
{
rotation = (360 - rotation) % 360;
}
// Add rotation metadata to preview stream
var props = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
props.Properties.Add(RotationKey, rotation);
await mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);
}
private async Task TakePhotoAsync()
{
var stream = new InMemoryRandomAccessStream();
await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
try
{
var file = await captureFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.GenerateUniqueName);
var orientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
await ReencodeAndSavePhotoAsync(stream, file, orientation);
}
catch (Exception ex)
{
Debug.WriteLine("Exception when taking photo: " + ex.ToString());
}
}
private async Task CleanupCameraAsync()
{
if (isInitialized)
{
if (isPreviewing)
{
await StopPreviewAsync();
}
isInitialized = false;
}
if (mediaCapture != null)
{
mediaCapture.Dispose();
mediaCapture = null;
}
}
#endregion Media Capture
#region Helpers
private async Task SetupUIAsync()
{
// Lock page to landscape to prevent the capture element from rotating
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
/*// Hide status bar
if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
{
await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
}*/
displayOrientation = displayInformation.CurrentOrientation;
if (orientationSensor != null)
{
deviceOrientation = orientationSensor.GetCurrentOrientation();
}
RegisterEventHandlers();
var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
// Fallback to local app storage if no pictures library
captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
}
private async Task CleanupUIAsync()
{
UnregisterEventHandlers();
/*if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
{
await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();
}*/
// Revert orientation preferences
DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;
}
private void RegisterEventHandlers()
{
/*if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
{
HardwareButtons.CameraPressed += OnHardwareCameraButtonPressed;
}*/
if (orientationSensor != null)
{
orientationSensor.OrientationChanged += OnOrientationSensorOrientationChanged;
}
displayInformation.OrientationChanged += OnDisplayInformationOrientationChanged;
systemMediaControls.PropertyChanged += OnSystemMediaControlsPropertyChanged;
takePhotoButton.Click += OnTakePhotoButtonClicked;
}
private void UnregisterEventHandlers()
{
/*if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
{
HardwareButtons.CameraPressed -= OnHardwareCameraButtonPressed;
}*/
if (orientationSensor != null)
{
orientationSensor.OrientationChanged -= OnOrientationSensorOrientationChanged;
}
displayInformation.OrientationChanged -= OnDisplayInformationOrientationChanged;
systemMediaControls.PropertyChanged -= OnSystemMediaControlsPropertyChanged;
takePhotoButton.Click -= OnTakePhotoButtonClicked;
}
private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation orientation)
{
using (var inputStream = stream)
{
var decoder = await BitmapDecoder.CreateAsync(inputStream);
using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
var properties = new BitmapPropertySet
{
{
"System.Photo.Orientation", new BitmapTypedValue(orientation, Windows.Foundation.PropertyType.UInt16)
}
};
await encoder.BitmapProperties.SetPropertiesAsync(properties);
await encoder.FlushAsync();
}
}
}
#endregion Helpers
#region Rotation
private SimpleOrientation GetCameraOrientation()
{
if (externalCamera)
{
// Cameras that aren't attached to the device do not rotate along with it
return SimpleOrientation.NotRotated;
}
var result = deviceOrientation;
// On portrait-first devices, the camera sensor is mounted at a 90 degree offset to the native orientation
if (displayInformation.NativeOrientation == DisplayOrientations.Portrait)
{
switch (result)
{
case SimpleOrientation.Rotated90DegreesCounterclockwise:
result = SimpleOrientation.NotRotated;
break;
case SimpleOrientation.Rotated180DegreesCounterclockwise:
result = SimpleOrientation.Rotated90DegreesCounterclockwise;
break;
case SimpleOrientation.Rotated270DegreesCounterclockwise:
result = SimpleOrientation.Rotated180DegreesCounterclockwise;
break;
case SimpleOrientation.NotRotated:
result = SimpleOrientation.Rotated270DegreesCounterclockwise;
break;
}
}
// If the preview is mirrored for a front-facing camera, invert the rotation
if (mirroringPreview)
{
// Rotating 0 and 180 ddegrees is the same clockwise and anti-clockwise
switch (result)
{
case SimpleOrientation.Rotated90DegreesCounterclockwise:
return SimpleOrientation.Rotated270DegreesCounterclockwise;
case SimpleOrientation.Rotated270DegreesCounterclockwise:
return SimpleOrientation.Rotated90DegreesCounterclockwise;
}
}
return result;
}
private static int ConvertDeviceOrientationToDegrees(SimpleOrientation orientation)
{
switch (orientation)
{
case SimpleOrientation.Rotated90DegreesCounterclockwise:
return 90;
case SimpleOrientation.Rotated180DegreesCounterclockwise:
return 180;
case SimpleOrientation.Rotated270DegreesCounterclockwise:
return 270;
case SimpleOrientation.NotRotated:
default:
return 0;
}
}
private static int ConvertDisplayOrientationToDegrees(DisplayOrientations orientation)
{
switch (orientation)
{
case DisplayOrientations.Portrait:
return 90;
case DisplayOrientations.LandscapeFlipped:
return 180;
case DisplayOrientations.PortraitFlipped:
return 270;
case DisplayOrientations.Landscape:
default:
return 0;
}
}
private static PhotoOrientation ConvertOrientationToPhotoOrientation(SimpleOrientation orientation)
{
switch (orientation)
{
case SimpleOrientation.Rotated90DegreesCounterclockwise:
return PhotoOrientation.Rotate90;
case SimpleOrientation.Rotated180DegreesCounterclockwise:
return PhotoOrientation.Rotate180;
case SimpleOrientation.Rotated270DegreesCounterclockwise:
return PhotoOrientation.Rotate270;
case SimpleOrientation.NotRotated:
default:
return PhotoOrientation.Normal;
}
}
#endregion Rotation
#region Lifecycle
private async void OnAppSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
await CleanupCameraAsync();
await CleanupUIAsync();
deferral.Complete();
}
private async void OnAppResuming(object sender, object o)
{
await SetupUIAsync();
await InitializeCameraAsync();
}
private async void OnPageUnloaded(object sender, RoutedEventArgs e)
{
await CleanupCameraAsync();
await CleanupUIAsync();
}
#endregion Lifecycle
}
}
This idea is pretty logic, you have a basic page, but which have renderer that preview the camera in the background, I mean, this is the idea I understood, however, it only gives you a white screen that throws an exception… (x86)
Exception initializing MediaCapture - \\?\USB#VID_045E&PID_0779&MI_00#6&2E9BBB25&0&0000#{e5323777-f976-4f5b-9b55-b94699c46e44}\GLOBAL: System.Runtime.InteropServices.COMException (0xC00DABE6): The current capture source does not have an independent photo stream.
The current capture source does not have an independent photo stream.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at CameraPreviewProject.UWP.Sources.PageRenderers.CameraPageRenderer.<InitializeCameraAsync>d__25.MoveNext()
Then I click the button of the downside woft menu and get:
Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Private.CoreLib.ni.dll
WinRT information: This object needs to be initialized before the requested operation can be carried out.
I’m a Xamarin Fan, but on that part, I’m not. This link about MediaCapture can be interesting though!
CameraView
To be honest, it’s so way easier to have a control as a button!
<Camera/>
Well, let’s have a look at it! I found a couple of solutions:
Moment MVVM logic - It seems to work only with Android & iOS
Xlabs Camera Unable to try since I can’t start VS2017 from the .sln. Also, I couldn't test the UWP side because it's an MVVM logic..
Xam.Plugin.Media This solution works on UWP !! But run a new activity/instance/page with a native design, so this isn't the solution searched
So, my question is “Does someone could create an element public class Camera() that can be used and declared as a simple xamarin forms button?”
Because, I saw as well 2 others projects about it, one I can’t remember, but the second one is Barcode Scanning but I’m not able to understand or take back the code to implement it as I would like…
It seems so easy and it’s so hard to get, why? Because finally, we’re talking about a view/image that displays a stream from a camera? A camera is just a service where you have methods such as TakePictureAsync() or anything like that? Rotate(), Switch(ViewSide vs), etc etc?
So, I searched about getting a frame view or display the stream of the camera into an image or a view.. I began from those links:
UWP get live webcam video stream by David Pine
UWP stream Webcam over socket to mediaElement I just made some changes
because the subject is a bit different, but.. I couldn't make it work
To be honest, I don’t know what to try now… I’m lost because, at the same time, I tried some Xamarin Forms solution, but also some proper UWP solutions and … nothing…. Maybe my point of view is not good, maybe my idea and just on the side, maybe I should try another approach, I don’t know at all..
I was also thinking about creating a class with some interface that I redefine in each platform renderer, but, still nothing…
Do you have please, any idea or any approach?
Note I have cross-posed this to the Xamarin forums.

Xamarin - Make rotations with CoreGraphics.CGAffineTransform

I want to make a UI Image rotate while content is downloading and I can't seem to make it rotate.
I have this event:
public override void ViewDidAppear(bool animated)
{
NoConnectionView.Hidden = CheckConnectivityStatus();
Task.Run(async () => await StartSpinningAnimation(true));
}
Which then fires this method:
protected async Task StartSpinningAnimation(bool IsSpinning)
{
do
{
UpdateActiveImage.Transform = CoreGraphics.CGAffineTransform.MakeRotation((float)Math.PI / 4);
}
while (IsSpinning);
return;
}
The page will eventually change after files are downloaded so I just want it to spin forever. It does animate at all. Does anyone have any ideas?
Using C# and Xamarin.iOS to develop iOS is a letter bit different from the Native language, Whenever you want to invoke some UI element in your background thread(like you need make some UI do an animation), you must use:
InvokeOnMainThread(delegate {
//Do something related UI stuff
});
If you add a try catch for it, you will get the exception like that "You are calling a method that can only be invoked in UI thread";
And by the way, you can not just use a do while to make an animation, I write a sample for you, you can take a look:
public partial class ViewController : UIViewController
{
bool needAnimate = true;
int count = 0;
UIView animationView = new UIView();
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
animationView.Frame = new CoreGraphics.CGRect (50, 50, 100, 100);
animationView.BackgroundColor = UIColor.Red;
this.Add (animationView);
this.View.AddGestureRecognizer (new UITapGestureRecognizer (() => {
Task.Run(async () => await StartAnimation());
}));
}
private async Task StartAnimation()
{
do
{
Console.WriteLine ("count = " + count++);
InvokeOnMainThread(delegate {
UIView.Animate(0.25,delegate {
animationView.Transform = CoreGraphics.CGAffineTransform.MakeRotation((float)Math.PI / 4 * (count/4 + 1));
});
});
System.Threading.Thread.Sleep(250);
}
while (needAnimate);
return;
}
public override void DidReceiveMemoryWarning ()
{
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
}
The animation is not smoothly, you need to optimize it yourself.
If you still have some questions, just leave here, I will check it latter.
Hope it can help you and welcome to Xamarin.
I would use UIView.AnimateNotify to perform the animation with CoreGraphics and totally avoid spin-loops to do something like this.
Example that spins an image 180 degrees and back repeating forever until stopped:
bool _animateStopping = false;
protected void SpinningAnimation(bool animate)
{
if (_animateStopping) return;
_animateStopping = !animate;
if (animate)
{
UIView.AnimateNotify(1,
() =>
{
image.Transform = CGAffineTransform.MakeRotation((nfloat)(Math.PI)); // in one second, spin 180 degrees
},
(bool finished) =>
{
UIView.AnimateNotify(1,
() =>
{
image.Transform = CGAffineTransform.MakeRotation(0); // in one second, spin it back
},
(bool finished2) =>
{
SpinningAnimation(true);
});
});
}
else {
UIView.AnimateNotify(1,
() =>
{
image.Alpha = 0; // fade away in one second
},
(bool finished) =>
{
image.RemoveFromSuperview();
_animateStopping = false;
}
);}
}
Usage:
image = new UIImageView(new CGRect(100, 100, 100, 100));
image.Image = UIImage.FromFile("wag.png");
Add(image);
SpinningAnimation(true);
await Task.Delay(5000); // simulate performing downloads, when done stop the animiation
SpinningAnimation(false);

Slowly initialized components that cause lack of user experience

This is the view that appears when I click a button on a previous view.
The text boxes, the smiling face image and the labels are predesigned created by xCode.
Please see the image and the code of the view to clear why all the view's components are initializing very slowly and getting ready to give the last shoot that is captured by me when it is finished to be totally loaded . Moreover, It is very slow when I type letters, the letters are appearing very slowly while I am typing with the keyboard that iOS provides on every touch on the text box.
The Code of The View;
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace IstanbulCity
{
public partial class AskForNAme : UIViewController
{
public delegate void AskForNAmeClosingDelegate (AskForNAme form);
public event AskForNAmeClosingDelegate AskForNAmeClosed;
NSObject obs1;
float scrollamount = 0.0f;
float bottomPoint = 0.0f;
float yOffset = 0.2f;
bool moveViewUp = false;
public AskForNAme () : base ("AskForNAme", null)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(true);
obs1 = NSNotificationCenter.DefaultCenter.AddObserver (
"UIKeyboardDidShowNotification", KeyboardUpNotification);
this.tbOwnerMailAdress.ShouldReturn += TextFieldShouldReturn;
this.tbOwnerBirthDay.ShouldReturn += TextFieldShouldReturn;
this.uivGuguPhoto.Image = UIImage.FromFile ("image/fcuk.jpeg");
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(false);
obs1 = NSNotificationCenter.DefaultCenter.AddObserver (
"UIKeyboardDidShowNotification", KeyboardUpNotification);
this.tbOwnerMailAdress.ShouldReturn += TextFieldShouldReturn;
this.tbOwnerBirthDay.ShouldReturn += TextFieldShouldReturn;
this.uivGuguPhoto.Image = UIImage.FromFile ("image/fcuk.jpeg");
}
public override void ViewDidUnload ()
{
base.ViewDidUnload ();
// Clear any references to subviews of the main view in order to
// allow the Garbage Collector to collect them sooner.
//
// e.g. myOutlet.Dispose (); myOutlet = null;
ReleaseDesignerOutlets ();
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
}
void HandleIstanbulCityViewControllerClosed (babyAge form)
{
form.DismissModalViewControllerAnimated (true);
form = null;
}
partial void tbKadikoyHallEditDidEndOnExit (MonoTouch.Foundation.NSObject sender)
{
tbIstanbulName.ResignFirstResponder ();
}
private bool TextFieldShouldReturn (UITextField tf)
{
tf.ResignFirstResponder ();
if (moveViewUp) {
ScrollTheView (false);
}
return true;
}
private void KeyboardUpNotification (NSNotification notification)
{
ResetTheView ();
RectangleF r = UIKeyboard.BoundsFromNotification (notification);
if (this.tbOwnerMailAdress.IsEditing ) {
//Calculate the bottom of the Texbox
//plus a small margin...
bottomPoint = (this.tbOwnerMailAdress.Frame.Y + this.tbOwnerMailAdress.Frame.Height + yOffset);
//Calculate the amount to scroll the view
//upwards so the Textbox becomes visible...
//This is the height of the Keyboard -
//(the height of the display - the bottom
//of the Texbox)...
scrollamount = (r.Height - (View.Frame.Size.Height - bottomPoint));
}
else if (this.tbOwnerBirthDay.IsEditing)
{
bottomPoint = (this.tbOwnerBirthDay.Frame.Y + this.tbOwnerBirthDay.Frame.Height + yOffset);
scrollamount = (r.Height - (View.Frame.Size.Height - bottomPoint));
}
else
{
scrollamount = 0;
}
//Check to see whether the view
//should be moved up...
if (scrollamount > 0) {
moveViewUp = true;
ScrollTheView (moveViewUp);
} else
moveViewUp = false;
}
private void ResetTheView ()
{
UIView.BeginAnimations (string.Empty, System.IntPtr.Zero);
UIView.SetAnimationDuration (0.3);
RectangleF frame = View.Frame;
frame.Y = 0;
View.Frame = frame;
UIView.CommitAnimations ();
}
private void ScrollTheView (bool movedUp)
{
//To invoke a views built-in animation behaviour,
//you create an animation block and
//set the duration of the move...
//Set the display scroll animation and duration...
UIView.BeginAnimations (string.Empty, System.IntPtr.Zero);
UIView.SetAnimationDuration (0.3);
//Get Display size...
RectangleF frame = View.Frame;
if (movedUp) {
//If the view should be moved up,
//subtract the keyboard height from the display...
frame.Y -= scrollamount;
} else {
//If the view shouldn't be moved up, restore it
//by adding the keyboard height back to the original...
frame.Y += scrollamount;
}
//Assign the new frame to the view...
View.Frame = frame;
//Tell the view that your all done with setting
//the animation parameters, and it should
//start the animation...
UIView.CommitAnimations ();
}
}
}
The Recent Version - Still The Same User Experience' slow!
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace IstanbulCity
{
public partial class AskForNAme : UIViewController
{
public delegate void AskForNAmeClosingDelegate (AskForNAme form);
public event AskForNAmeClosingDelegate AskForNAmeClosed;
public AskForNAme () : base ("AskForNAme", null)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void ViewDidUnload ()
{
base.ViewDidUnload ();
// Clear any references to subviews of the main view in order to
// allow the Garbage Collector to collect them sooner.
//
// e.g. myOutlet.Dispose (); myOutlet = null;
ReleaseDesignerOutlets ();
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
}
void HandleIstanbulCityViewControllerClosed (babyAge form)
{
form.DismissModalViewControllerAnimated (true);
form = null;
}
}
}
This does not look to be initialization related. You are adding notifications from both ViewDidAppear and ViewWillAppear. You're also always calling ResetTheView, which does animations, on every keyboard notification (even if nothing else changed).
My guess is that you are calling ResetTheView way more often that you realize - and the continuous animations are killing the performance of your application.
You can confirm this by putting a Console.WriteLine, and maybe a counter, in the ResetTheView method.

Why don't InfoCards work in IE8?

What changed in IE8 that makes detecting InfoCard Selector support in javascript stop working unless IE8 is put in Compatibility Mode?
And more to the point, what is the new JavaScript code to detect the presence of InfoCard support?
Here is the script that worked up through IE7, including FireFox with a plug-in in some cases:
function AreCardsSupported() {
var IEVer = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
if (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) {
IEVer = parseFloat(RegExp.$1);
}
}
// Look for IE 7+.
if (IEVer >= 7) {
var embed = document.createElement("object");
embed.setAttribute("type", "application/x-informationcard");
return "" + embed.issuerPolicy != "undefined" && embed.isInstalled;
}
// not IE (any version)
if (IEVer < 0 && navigator.mimeTypes && navigator.mimeTypes.length) {
// check to see if there is a mimeType handler.
x = navigator.mimeTypes['application/x-informationcard'];
if (x && x.enabledPlugin) {
return true;
}
// check for the IdentitySelector event handler is there.
if (document.addEventListener) {
var event = document.createEvent("Events");
event.initEvent("IdentitySelectorAvailable", true, true);
top.dispatchEvent(event);
if (top.IdentitySelectorAvailable == true) {
return true;
}
}
}
return false;
}
I got an answer out of band from the IE8 team:
Change
embed.setAttribute("type", "application/x-informationcard");
to
embed.type = "application/x-informationcard";

Resources