Xamarin.Forms: Get native image from ImageSource
Sometimes we need to implement images in our custom renderers and as a first solution most of developers take the decision to use a string property but for me is not the better and standard way to manage image resources on Xamarin.Forms, in this blog we will take a look to a helper class that help us to manage images resource on your Xamairn.Forms renderers using a IImageSourceHandler.
There are three IImageSourceHandler helper classes:
1. ImageLoaderSourceHandler: Handle the Uri resources
2. FileImageSourceHandler: Handle the local/embed resources
3. StreamImagesourceHandler: Handle the stream image resources
The first that we need is to check what kind of source have your ImageSource property using the next code
after this, with the returned IImageSourceHandler you can call the LoadImageAsync and passing the source that you want to be native and this method will be return for you an UIImage for iOS or a Bitmap for Android
After this you will be able to implement the heartbeat control using your own imagesource and start/stop the "heartbeat" animation using the "IsBeating" property.
Screenshots of the example control
There are three IImageSourceHandler helper classes:
1. ImageLoaderSourceHandler: Handle the Uri resources
2. FileImageSourceHandler: Handle the local/embed resources
3. StreamImagesourceHandler: Handle the stream image resources
The first that we need is to check what kind of source have your ImageSource property using the next code
after this, with the returned IImageSourceHandler you can call the LoadImageAsync and passing the source that you want to be native and this method will be return for you an UIImage for iOS or a Bitmap for Android
Real World Example: "HeartBeatView" Control
Now we will create an example control using the previous code, we have 4 key file
1. HeartBeatView.cs: Contains the main forms control class.
2. ImageSourceExtensions.cs: Contains the "GetNativeHandler" ImageSource extension method.
3. Android: HeartBeatViewRenderer.cs: Contains the Android custom renderer code for HeartBeatView control.
4. iOS: HeartBeatViewRenderer.cs: Contains the iOS custom renderer code for HeartBeatView control.
After this you will be able to implement the heartbeat control using your own imagesource and start/stop the "heartbeat" animation using the "IsBeating" property.
Screenshots of the example control
Full Example Code: https://github.com/AlejandroRuiz/HeartBeatXForms
Comentarios
Publicar un comentario