Search This Blog

Monday 16 July 2018

Xamarin Android: Create Circle Image using custom renderer




XAML File
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:customImage="clr-namespace:CircleImagePRoject"
             x:Class="CircleImagePRoject.MainPage">
    <StackLayout VerticalOptions="Center">
        <Label Text="Create Circle Image Using Xamarin Form" HorizontalOptions="Center" ></Label>
        <Image Source="Users"  HorizontalOptions="Center" VerticalOptions="Center"   HeightRequest="80" WidthRequest="80"></Image>
        <customImage:CircleImageRenderer  Source="Users"  HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="80" WidthRequest="80" ></customImage:CircleImageRenderer>
    </StackLayout>
</ContentPage>



In a Xamarin.Forms Project Create Renderer

CircleImageRenderer.cs
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
 
namespace CircleImagePRoject
{
   public  class CircleImageRenderer:Image
    {
    }
}
 

Xamarin Android Renderer

CircleImage.cs
using System;
using Android.Content;
using Android.Graphics;
using CircleImagePRoject;
using CircleImagePRoject.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
 
[assembly: ExportRenderer(typeof(CircleImageRenderer), typeof(CircleImage))]
namespace CircleImagePRoject.Droid
{
    class CircleImage : ImageRenderer
    {
        public CircleImage(Context context) : base(context)
        {
 
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement == null)
            {
                if ((int)Android.OS.Build.VERSION.SdkInt < 18)
                {
                    SetLayerType(Android.Views.LayerType.Software, null);
                }
            }
        }
        protected override bool DrawChild(Canvas canvas, Android.Views.View child, long drawingTime)
        {
            try
            {
                var radius = Math.Min(Width, Height) / 2;
                var strokeWidth = 10;
                radius -= strokeWidth / 2;
 
                //Create path to clip
                var path = new Path();
                path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
                canvas.Save();
                canvas.ClipPath(path);
 
                var result = base.DrawChild(canvas, child, drawingTime);
 
                canvas.Restore();
 
                // Create path for circle border
                path = new Path();
                path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
 
                var paint = new Paint();
                paint.AntiAlias = true;
                paint.StrokeWidth = 5;
                paint.SetStyle(Paint.Style.Stroke);
                paint.Color = global::Android.Graphics.Color.White;
 
                canvas.DrawPath(path, paint);
 
                //Properly dispose
                paint.Dispose();
                path.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                // Debug.WriteLine("Unable to create circle image: " + ex);
            }
 
            return base.DrawChild(canvas, child, drawingTime);
        }
    }
}
 









Saturday 14 July 2018

How to format date and time in XAML in Xamarin application

<Label Text = “{Binding Date, StringFormat=’create at : { 0:dddd dd MMMM } ‘“} />
output : sunday 27 August

Date Format


How to start emulator through command promt





Starting the emulator



Use the emulator command to start the emulator, as an alternative to running your project or starting it through the AVD Manager.
Here's the basic command-line syntax for starting a virtual device from a terminal prompt:
emulator -avd avd_name [ {-option [value]} … ]
Or
emulator @avd_name [ {-option [value]} … ]
For example, if you launch the emulator from within Android Studio running on a Mac, the default command line will be similar to the following:
$ /Users/janedoe/Library/Android/sdk/tools/emulator -avd Nexus_5X_API_23 -netdelay none -netspeed full
You can specify startup options when you start the emulator, but not later on.
For a list of AVD names, enter the following command:
emulator -list-avds

Tuesday 10 July 2018

Xamarin IOS play and record audio

for start, play and stop recording call interface using dependency service

// write this code on the click event of button or tap gesture event of any control

start recording:
DependencyService.Get<IAudioRecorder>().StartRecording(); //click on start record button
play recording:
DependencyService.Get<IAudioRecorder>().PlayRecording(); //click on play record button
stop recording:
DependencyService.Get<IAudioRecorder>().StopRecording(); //click on stop record button
 

Create the Interface in your Xamarin Form Project 
using System;
namespace AudioRecorderProject.Interfaces
{
    public interface IAudioRecorder
    {
        void StartRecording();
        void StopRecording();
        void PlayRecording();
    }
}
 


Create the audio recorder class in your IOS Project that inherit the interface IAudioRecorder
using System;
using AudioRecorderProject.Interfaces;
using AVFoundation;
using AudioRecorderProject.iOS;
using Foundation;
using System.IO;
using UIKit;
 
[assembly:Xamarin.Forms.Dependency(typeof(AudioRecorder))]
namespace AudioRecorderProject.iOS
{
    public class AudioRecorder : IAudioRecorder
    {
 
        AVAudioRecorder recorder;
        AVPlayer player;
        NSError error;
        NSUrl url;
        NSDictionary settings;
        string audioFilePath;
 
 
        public void StartRecording()
        {
            var audioSession = AVAudioSession.SharedInstance();
            var err = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord); 
            string fileName = string.Format("Myfile{0}.wav", DateTime.Now.ToString("yyyyMMddHHmmss"));
            audioFilePath = Path.Combine(Path.GetTempPath(), fileName);
            url = NSUrl.FromFilename(audioFilePath);
            NSObject[] values = new NSObject[]
            {
                NSNumber.FromFloat(44100.0f),
                NSNumber.FromInt32 ((int)AudioToolbox.AudioFormatType.LinearPCM),//AVFormat
                NSNumber.FromInt32 (2), //Channels
                NSNumber.FromInt32 (16), //PCMBitDepth 
                NSNumber.FromBoolean (false), //IsBigEndianKey 
                NSNumber.FromBoolean (false) //IsFloatKey
            };
            NSObject[] keys = new NSObject[]
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVLinearPCMBitDepthKey,
                AVAudioSettings.AVLinearPCMIsBigEndianKey,
                AVAudioSettings.AVLinearPCMIsFloatKey
            };
            settings = NSDictionary.FromObjectsAndKeys(values, keys);
            recorder = AVAudioRecorder.Create(url, new AudioSettings(settings), out error);
            recorder.PrepareToRecord();
            recorder.Record();
 
        }
 
 
        public void PlayRecording()
        {
            url = NSUrl.FromFilename(audioFilePath);
            var asset = AVAsset.FromUrl(url);
            var playerItem = new AVPlayerItem(asset);
            player = new AVPlayer(playerItem);
            var playerLayer = AVPlayerLayer.FromPlayer(player);
            GetController().View.Layer.AddSublayer(playerLayer);
            player.Play();
        } 
 
       public void StopRecording()
        {
            if(recorder!=null){
                recorder.Stop();
            }
        } 
       private static UIViewController GetController()
        {
            var vc = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (vc.PresentedViewController != null)
                vc = vc.PresentedViewController;
            return vc;
        } 
   }
 
}


Note: Add the NSMicrophoneUsageDescription key value in the Source tab of the Info.plist file. This is added by selecting "Privacy – Microphone Usage Description" from the property drop down, and setting an appropriate string:









Tuesday 3 July 2018

Adding a button to the title bar Xamarin Forms

Add following code in Xaml

 <ContentPage.ToolbarItems>
         <ToolbarItem Icon="icon.png" Text="Write Post" Clicked="writePost_Clicked" ></ToolbarItem>
 </ContentPage.ToolbarItems>

Sunday 1 July 2018

Google Play - Lost Keystore Files

Reset Google Play  Keystore file

You can reset Keystore file if your app Signing is enable
Go to your google play console and check in Release management that your App Signing was enable



Click on following link for get more details about it

https://support.google.com/googleplay/android-developer/answer/7384423?hl=en

Popular Posts