Xamarin.Android Camera Touch to Focus - xamarin

I am using Xamarin.Android to use inbuilt camera app to take a photo
but there are two missed things that I cant do and I have been googling them for long time:
I want to get a msg or popup (anything) after pressing the button to take a photo like "photo taken"
I want to let the user focus on any point of the camera - TAP TO FOCUS
async void TakePhotoButtonTapped(object sender, EventArgs e)
{
camera.StopPreview();
Android.Hardware.Camera.Parameters parameters = camera.GetParameters();
parameters.FocusMode = global::Android.Hardware.Camera.Parameters.FocusModeAuto;
camera.SetParameters(parameters);
var image = textureView.Bitmap;
try
{
var absolutePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim).AbsolutePath;
var folderPath = absolutePath + "/Camera";
var filePath = System.IO.Path.Combine(folderPath, string.Format("photo_{0}.jpg", Guid.NewGuid()));
var fileStream = new FileStream(filePath, FileMode.Create);
await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 92, fileStream);
fileStream.Close();
image.Recycle();
var intent = new Android.Content.Intent(Android.Content.Intent.ActionMediaScannerScanFile);
var file = new Java.IO.File(filePath);
var uri = Android.Net.Uri.FromFile(file);
intent.SetData(uri);
MainActivity.Instance.SendBroadcast(intent);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(#" ", ex.Message);
}
camera.StartPreview();
}
I tried this but not working:
public void OnAutoFocus(bool success, Android.Hardware.Camera camera)
{
var parameters = camera.GetParameters();
if (parameters.FocusMode != Android.Hardware.Camera.Parameters.FocusModeContinuousPicture)
{
parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeContinuousPicture;
if (parameters.MaxNumFocusAreas > 0)
{
parameters.FocusAreas = null;
}
camera.SetParameters(parameters);
camera.StartPreview();
}
}
public bool OnTouch(Android.Views.View view, MotionEvent e)
{
if (camera != null)
{
var parameters = camera.GetParameters();
camera.CancelAutoFocus();
Rect focusRect = CalculateTapArea(e.GetX(), e.GetY(), 1f);
if (parameters.FocusMode != Android.Hardware.Camera.Parameters.FocusModeAuto)
{
parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeAuto;
}
if (parameters.MaxNumFocusAreas > 0)
{
List<Area> mylist = new List<Area>();
mylist.Add(new Android.Hardware.Camera.Area(focusRect, 1000));
parameters.FocusAreas = mylist;
}
try
{
camera.CancelAutoFocus();
camera.SetParameters(parameters);
camera.StartPreview();
camera.AutoFocus(this);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
Console.Write(ex.StackTrace);
}
return true;
}
return false;
}
private Rect CalculateTapArea(object x, object y, float coefficient)
{
var focusAreaSize = 500;
int areaSize = Java.Lang.Float.ValueOf(focusAreaSize * coefficient).IntValue();
int left = clamp((int) x - areaSize / 2, 0, textureView.Width - areaSize);
int top = clamp((int) y - areaSize / 2, 0, textureView.Height - areaSize);
RectF rectF = new RectF(left, top, left + areaSize, top + areaSize);
Matrix.MapRect(rectF);
return new Rect((int) System.Math.Round(rectF.Left), (int) System.Math.Round(rectF.Top), (int) System.Math.Round(rectF.Right),
(int) System.Math.Round(rectF.Bottom));
}
private int clamp(int x, int min, int max)
{
if (x > max)
{
return max;
}
if (x < min)
{
return min;
}
return x;
}

For focusing the camera when touching the preview you will need to:
Add a touch event handler to listen for the user touching the preview
Get the X and Y coordinates from that touch event, which are usually in the event arguments
Create a rectangle to focus to tell the Android Camera where to focus and in which area
Set FocusAreas and MeteringAreas on Camera.Parameters from your rectangle
Set the new Camera.Parameters on the camera
Set a AutoFocus callback on the camera
When the callback triggers, remove the callback from the camera, and cancel auto focus
To notify the user about a picture being taken, you can use a Toast or create a area in your preview where you want to show such messages. It is entirely up to you how you want to notify the user.

Related

XamarinForms sticky header

Im searching for a solution represented here as a gif from my designer: enter link description here
Basically, I need a list, with a header, or with a another view (grid, or stacklayout). On a scroll, I need to catch event (scrolling down, scrolling up) and to move list with that header.
Can you suggest me some referrals?
Here is the example code from syncfusion:
https://www.syncfusion.com/downloads/support/directtrac/general/ze/AnimateHeaderOnScroll1119606059
You can achieve your requirement by handling Scrolled event as below,
public MainPage()
{
InitializeComponent();
container = _listView.GetVisualContainer();
_scrollView = _listView.GetScrollView();
_scrollView.Scrolled += ScrollView_Scrolled;
}
private void ScrollView_Scrolled(object sender, ScrolledEventArgs e)
{
scrollOffet = (double)container.GetType().GetRuntimeProperties().First(p => p.Name == "ScrollOffset").GetValue(container);
if (e.ScrollY == 0)
(BindingContext as MainViewModel).CanPassTouch = true;
}
private void PanGestureRecognizer_PanUpdated(object sender, PanUpdatedEventArgs e)
{
if(e.StatusType == GestureStatus.Running)
{
var y = e.TotalY;
//Up scroll
if (y < 0)
{
if (!_originalHeaderHeight.HasValue)
{
_originalHeaderHeight = _headerView.Height;
}
var newHeight = _originalHeaderHeight.Value + y;
_headerView.HeightRequest = newHeight > MIN_HEADER_HEIGHT ? newHeight : MIN_HEADER_HEIGHT;
}
//Down scroll
else
{
if (!_originalHeaderHeight.HasValue)
{
_originalHeaderHeight = _headerView.Height;
}
var newHeight = _originalHeaderHeight.Value + y;
_headerView.HeightRequest = newHeight < MAX_HEADER_HEIGHT ? newHeight : MAX_HEADER_HEIGHT;
}
//Enable InputTransparent for SfListView, to enable the ListView scrolling
//after reaching the Header min/max heights based on scrolling.
if (_headerView.HeightRequest == MIN_HEADER_HEIGHT && y < 0)
(BindingContext as MainViewModel).CanPassTouch = false;
if (_headerView.HeightRequest == MAX_HEADER_HEIGHT && scrollOffet > 0)
(BindingContext as MainViewModel).CanPassTouch = false;
}
}
Sample

Video Recorder inside a app using xamarin forms

How can I implement a video recorder inside an application using xamarin forms?
You can use Xamarin.Plugin.Media. If it is not flexible enough for you, then you need to implement the video recorder using the native APIs. In which case you probably shouldn't be doing Xamarin.Forms at all, but if you insist that is the way.
Do you want to achieve the result like following GIF(Over 2M, SO cannot allow upload it )?
https://imgur.com/a/kpMl2ed
I achieve it in android by custom rendere. Here is code.
First of all, we should MediaRecorder to record the video.
public void startRecord(SurfaceView surfaceView)
{
Device.BeginInvokeOnMainThread(() => {
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
recorder = new MediaRecorder();
//If you want to rotate the video screen, you can use following code
//Camera camera = Camera.Open();
//Camera.Parameters parameters = camera.GetParameters();
//parameters.SetPreviewSize(640, 480);
//parameters.SetPictureSize(640, 480);
//camera.SetParameters(parameters);
//camera.SetDisplayOrientation(90);
//camera.Unlock();
//recorder.SetCamera(camera);
recorder.SetVideoSource(VideoSource.Camera);
recorder.SetAudioSource(AudioSource.Mic);
recorder.SetOutputFormat(OutputFormat.Default);
recorder.SetVideoEncoder(VideoEncoder.Default);
recorder.SetAudioEncoder(AudioEncoder.Default);
recorder.SetOutputFile(path);
recorder.SetPreviewDisplay(surfaceView.Holder.Surface);
recorder.Prepare();
recorder.Start();
});
}
If you want to achieve the record the video inside the application, you should use custom renderer to view. Use SurfaceView to see the camera view.First of all. please create a CameraPreview
public sealed class CameraPreview : ViewGroup, ISurfaceHolderCallback
{
public SurfaceView surfaceView;
ISurfaceHolder holder;
Camera.Size previewSize;
IList<Camera.Size> supportedPreviewSizes;
Camera camera;
IWindowManager windowManager;
MediaRecorder recorder;
public bool IsPreviewing { get; set; }
public Camera Preview {
get { return camera; }
set {
camera = value;
if (camera != null) {
supportedPreviewSizes = Preview.GetParameters().SupportedPreviewSizes;
RequestLayout();
}
}
}
public CameraPreview (Context context)
: base (context)
{
surfaceView = new SurfaceView (context);
AddView (surfaceView);
windowManager = Context.GetSystemService (Context.WindowService).JavaCast<IWindowManager>();
IsPreviewing = false;
holder = surfaceView.Holder;
holder.AddCallback (this);
MessagingCenter.Subscribe<string>("111", "Hi", (expense) =>
{
startRecord(surfaceView);
});
MessagingCenter.Subscribe<string>("1112", "Hi2", (expense) =>
{
stopRecord(surfaceView);
});
}
private void stopRecord(SurfaceView surfaceView)
{
recorder.Stop();
recorder.Release();
}
public void startRecord(SurfaceView surfaceView)
{
Device.BeginInvokeOnMainThread(() => {
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
recorder = new MediaRecorder();
//If you want to rotate the video screen, you can use following code
//Camera camera = Camera.Open();
//Camera.Parameters parameters = camera.GetParameters();
//parameters.SetPreviewSize(640, 480);
//parameters.SetPictureSize(640, 480);
//camera.SetParameters(parameters);
//camera.SetDisplayOrientation(90);
//camera.Unlock();
//recorder.SetCamera(camera);
recorder.SetVideoSource(VideoSource.Camera);
recorder.SetAudioSource(AudioSource.Mic);
recorder.SetOutputFormat(OutputFormat.Default);
recorder.SetVideoEncoder(VideoEncoder.Default);
recorder.SetAudioEncoder(AudioEncoder.Default);
recorder.SetOutputFile(path);
recorder.SetPreviewDisplay(surfaceView.Holder.Surface);
recorder.Prepare();
recorder.Start();
});
}
protected override void OnMeasure (int widthMeasureSpec, int heightMeasureSpec)
{
int width = ResolveSize (SuggestedMinimumWidth, widthMeasureSpec);
int height = ResolveSize (SuggestedMinimumHeight, heightMeasureSpec);
SetMeasuredDimension (width, height);
if (supportedPreviewSizes != null) {
previewSize = GetOptimalPreviewSize (supportedPreviewSizes, width, height);
}
}
protected override void OnLayout (bool changed, int l, int t, int r, int b)
{
var msw = MeasureSpec.MakeMeasureSpec (r - l, MeasureSpecMode.Exactly);
var msh = MeasureSpec.MakeMeasureSpec (b - t, MeasureSpecMode.Exactly);
surfaceView.Measure (msw, msh);
surfaceView.Layout (0, 0, r - l, b - t);
}
public void SurfaceCreated (ISurfaceHolder holder)
{
try {
if (Preview != null) {
Preview.SetPreviewDisplay (holder);
}
} catch (Exception ex) {
System.Diagnostics.Debug.WriteLine (#" ERROR: ", ex.Message);
}
}
public void SurfaceDestroyed (ISurfaceHolder holder)
{
if (Preview != null) {
Preview.StopPreview ();
}
}
public void SurfaceChanged (ISurfaceHolder holder, Android.Graphics.Format format, int width, int height)
{
var parameters = Preview.GetParameters ();
parameters.SetPreviewSize (previewSize.Width, previewSize.Height);
RequestLayout ();
//If you want to rotate the video screen, you can use following code
//switch (windowManager.DefaultDisplay.Rotation) {
//case SurfaceOrientation.Rotation0:
// camera.SetDisplayOrientation (90);
// break;
//case SurfaceOrientation.Rotation90:
// camera.SetDisplayOrientation (0);
// break;
//case SurfaceOrientation.Rotation270:
// camera.SetDisplayOrientation (180);
// break;
//}
Preview.SetParameters (parameters);
Preview.StartPreview ();
IsPreviewing = true;
}
Camera.Size GetOptimalPreviewSize (IList<Camera.Size> sizes, int w, int h)
{
const double AspectTolerance = 0.1;
double targetRatio = (double)w / h;
if (sizes == null) {
return null;
}
Camera.Size optimalSize = null;
double minDiff = double.MaxValue;
int targetHeight = h;
foreach (Camera.Size size in sizes) {
double ratio = (double)size.Width / size.Height;
if (Math.Abs (ratio - targetRatio) > AspectTolerance)
continue;
if (Math.Abs (size.Height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.Abs (size.Height - targetHeight);
}
}
if (optimalSize == null) {
minDiff = double.MaxValue;
foreach (Camera.Size size in sizes) {
if (Math.Abs (size.Height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.Abs (size.Height - targetHeight);
}
}
}
return optimalSize;
}
}
Then, Here is custom renderer.
[assembly: ExportRenderer(typeof(CustomRenderer.CameraPreview), typeof(CameraPreviewRenderer))]
namespace CustomRenderer.Droid
{
public class CameraPreviewRenderer : ViewRenderer
{
CameraPreview cameraPreview;
public CameraPreviewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<CustomRenderer.CameraPreview> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Unsubscribe
cameraPreview.Click -= OnCameraPreviewClicked;
}
if (e.NewElement != null)
{
if (Control == null)
{
cameraPreview = new CameraPreview(Context);
SetNativeControl(cameraPreview);
}
Control.Preview = Camera.Open((int)e.NewElement.Camera);
// Subscribe
cameraPreview.Click += OnCameraPreviewClicked;
}
}
void OnCameraPreviewClicked(object sender, EventArgs e)
{
if (cameraPreview.IsPreviewing)
{
cameraPreview.Preview.StopPreview();
cameraPreview.IsPreviewing = false;
}
else
{
cameraPreview.Preview.StartPreview();
cameraPreview.IsPreviewing = true;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Control.Preview.Release();
}
base.Dispose(disposing);
}
}
}
If you want to know how to achieve Camera Preview in the IOS or UWP, you can refer to this link.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/view
Here is code in github.
https://github.com/851265601/FormsRecordVideoInside
Above way to achieve it, it a bit complexed. I suggest you to use the Xam.Plugin.Media to achieve it. Here is running GIF. it cannot see the video preview in the application, but you do not need to use custom renderer to achieve it just serveral lines code.
private async void PlayStopButtonText_Clicked(object sender, EventArgs e)
{
// throw new NotImplementedException();
var file = await CrossMedia.Current.TakeVideoAsync(new StoreVideoOptions
{
SaveToAlbum = true,Directory = "Sample"
});
//Get the public album path
if (file == null)
return;
await DisplayAlert("File Location", file.AlbumPath, "OK");
}
In the android, add the following permission.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Here is running GIF(Over 2M, SO cannot allow upload it ).
https://imgur.com/a/9WE4szZ

Round Shape Icon or Button On Bottom Tabbed Bar Xamarin Forms

I am trying to get the above look on my tabbed bar in xamarin forms, i tried customizing the tabbed bar using renderer and still was not able to get the expected output
output i am getting
till now this is what i have tried
[assembly: ExportRenderer(typeof(BottomNavTabPage), typeof(BottomNavTabPageRenderer))]
namespace HealthMobile.Droid.Renderers
{
public class BottomNavTabPageRenderer : TabbedPageRenderer
{
private bool _isShiftModeSet;
public BottomNavTabPageRenderer(Context context)
: base(context)
{
}
protected override void OnVisibilityChanged(Android.Views.View changedView, [GeneratedEnum] ViewStates visibility)
{
base.OnVisibilityChanged(changedView, visibility);
var tabs = changedView.FindViewById<TabLayout>(Resource.Id.sliding_tabs);
if (tabs != null)
{
ViewGroup vg = (ViewGroup)tabs.GetChildAt(0);
int tabsCount = vg.ChildCount;
}
}
//protected override void DispatchDraw (global::Android.Graphics.Canvas canvas)
// {
// base.DispatchDraw (canvas);
// SetTabIcons();
// // var tabLayout = (TabLayout)GetChildAt(1);
// }
// private void SetTabIcons()
// {
// var element = this.Element;
// if (null == element)
// {
// return;
// }
// Activity activity = this.Context as Activity;
// if ((null != activity) && (null != activity.ActionBar) && (activity.ActionBar.TabCount > 0))
// {
// for (int i = 0; i < element.Children.Count; i += 1)
// {
// var tab = activity.ActionBar.GetTabAt(i);
// var page = element.Children[i];
// if ((null != tab) && (null != page) && (null != page.Icon)
// && (tab.CustomView == null))
// {
// var resourceId = activity.Resources.GetIdentifier(page.Icon.File.ToLowerInvariant(), "drawable", this.Context.PackageName);
// LinearLayout tabHeader
// = new LinearLayout(activity) { Orientation = Orientation.Vertical };
// ImageView tabImg = new ImageView(activity);
// TextView tabTitle = new TextView(activity);
// tabImg.SetImageResource(resourceId);
// tabTitle.Text = page.Title;
// tabTitle.SetTextColor(Android.Graphics.Color.White);
// tabHeader.AddView(tabTitle);
// tabHeader.AddView(tabImg);
// tab.SetCustomView(tabHeader);
// }
// }
// }
// }
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
var childViews = GetAllChildViews(ViewGroup);
//tab.SetIcon(Resource.Drawable.icon);
var scale = Resources.DisplayMetrics.Density;
var paddingDp = 0;
var dpAsPixels = (int)(paddingDp * scale + 0.5f);
foreach (var childView in childViews)
{
if (childView is BottomNavigationItemView tab)
{
//tab.SetPadding(-50, -100, -50, -100);
}
else if (childView is TextView textView)
{
textView.SetTextColor(Android.Graphics.Color.Transparent);
}
}
}
protected override void SetTabIcon(TabLayout.Tab tab, FileImageSource icon)
{
base.SetTabIcon(tab, icon);
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
try
{
if (!_isShiftModeSet)
{
var children = GetAllChildViews(ViewGroup);
if (children.SingleOrDefault(x => x is BottomNavigationView) is BottomNavigationView bottomNav)
{
bottomNav.SetShiftMode(false, false);
_isShiftModeSet = true;
}
}
}
catch (Exception e)
{
Console.WriteLine($"Error setting ShiftMode: {e}");
}
}
private List<View> GetAllChildViews(View view)
{
if (!(view is ViewGroup group))
{
return new List<View> {view };
}
var result = new List<View>();
for (int i = 0; i < group.ChildCount; i++)
{
var child = group.GetChildAt(i);
var childList = new List<View> {child};
childList.AddRange(GetAllChildViews(child));
result.AddRange(childList);
}
return result.Distinct().ToList();
}
}
}
i am trying to make this look like this somewhat
output expecting
also i tried setting up the icons but SetTabIcons method never get triggered

getting a rotated image in my image view after taking from the camera as a portrait one

My requirement is to take picture from the camera or pick a image from the gallery and show it in a image view.. After showing the image I'm sending as a mail whatever the image is selected. My issues is every time i take a portrait picture form the camera it rotates and show it in the image view. How to fix this issue.
thanks in advance.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.skicka_bild_activity);
share = new Sharedprefs(SkickaBild.this);
emailSendButton = (Button) findViewById(R.id.skicka_button);
emailSendButton.setOnClickListener(this);
emailSendButton.setEnabled(false);
Button camaraOnButtton = (Button) findViewById(R.id.fotografera_button);
camaraOnButtton.setOnClickListener(this);
Button galleryOpenButton = (Button) findViewById(R.id.valj_bild_button);
galleryOpenButton.setOnClickListener(this);
imageSetImageView = (ImageView) findViewById(R.id.imageView_skick);
maxWidth = share.getmaxwidth();
mContentResolver = getContentResolver();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.skicka_button:
if (isImageViewFilled) {
showEmailComposer();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
SkickaBild.this);
builder.setTitle("Alert !!");
builder.setMessage("Pick a image before you send the email")
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
break;
case R.id.fotografera_button:
share.setisFromTabsClearImage(false);
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent takePictureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
mCapturedImageURI);
startActivityForResult(takePictureIntent, 0);
break;
case R.id.valj_bild_button:
share.setisFromTabsClearImage(false);
Intent pickPhoto = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(mCapturedImageURI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor
.getString(column_index_data);
Bitmap mImageBitmap = BitmapFactory
.decodeFile(capturedImageFilePath);
imageSetImageView.setImageBitmap(mImageBitmap);
isImageViewFilled = true;
if (isImageViewFilled) {
emailSendButton.setEnabled(true);
emailSendButton.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.skicka_button_black));
}
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
System.out.println("PICTURE PATH " + capturedImageFilePath);
pic = new File(capturedImageFilePath);
String cPath = pic.getAbsolutePath();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cPath, bmOptions);
float photoW = mImageBitmap.getWidth();
float photoH = mImageBitmap.getHeight();
// Get the dimensions of the View
float targetW = Float.parseFloat(maxWidth);
float targetH = (photoH / photoW) * targetW;
System.out.println("cam bitmap height"
+ mImageBitmap.getHeight());
System.out.println("cam bitmap weidth" + maxWidth);
System.out.println("cam bitmap Width 02 "
+ mImageBitmap.getWidth());
System.out.println("cam target Height " + targetH);
System.out.println("cam target width " + targetW);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = (int) scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(cPath, bmOptions);
mImageBitmap = Bitmap.createScaledBitmap(bitmap,
(int) targetW, (int) targetH, false);
FileOutputStream fout;
try {
fout = new FileOutputStream(pic);
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
fout);
fout.flush();
fout.close();
bitmap.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case 1:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
InputStream in = null;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
System.out.println("PICTUREPATH" + picturePath);
cursor.close();
Bitmap imageBitmap = BitmapFactory.decodeFile(picturePath);
int orientation = getOrientation(this, selectedImage);
System.out.println("ORIENTATION VALUE " + orientation);
imageSetImageView.setImageBitmap(imageBitmap);
isImageViewFilled = true;
if (isImageViewFilled) {
emailSendButton.setEnabled(true);
emailSendButton.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.skicka_button_black));
}
// ////////////////////////// Image is set ///////////////
pic = new File(picturePath);
String cPath = pic.getAbsolutePath();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cPath, bmOptions);
float photoW = imageBitmap.getWidth();
float photoH = imageBitmap.getHeight();
// Get the dimensions of the View
float targetW = Float.parseFloat(maxWidth);
float targetH = (photoH / photoW) * targetW;
System.out.println(" bitmap height"
+ imageBitmap.getHeight());
System.out.println(" bitmap weidth" + maxWidth);
System.out.println(" bitmap Width 02 "
+ imageBitmap.getWidth());
System.out.println(" target Height " + targetH);
System.out.println(" target width " + targetW);
float scaleFactor = Math.min(photoW / targetW, photoH
/ targetH);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = (int) scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(cPath, bmOptions);
imageBitmap = Bitmap.createScaledBitmap(bitmap,
(int) targetW, (int) targetH, false);
FileOutputStream fout;
fout = new FileOutputStream(pic);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
fout.flush();
fout.close();
bitmap.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
public static int getOrientation(Context context, Uri photoUri) {
String[] orientationColumn = { MediaStore.Images.Media.ORIENTATION };
Cursor cursor = context.getContentResolver().query(photoUri,
orientationColumn, null, null, null);
try {
if (cursor.moveToFirst()) {
return cursor.getInt(cursor
.getColumnIndex(orientationColumn[0]));
} else {
return -1;
}
} finally {
cursor.close();
}
}
private void showEmailComposer() {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { share.getMailTo() });
email.putExtra(Intent.EXTRA_SUBJECT, share.getsubject());
email.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
// email.putExtra(Intent.EXTRA_STREAM, pic.getName());
email.putExtra(Intent.EXTRA_TEXT, share.getemailbody());
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));
isEmailSend = true;
}
#Override
protected void onResume() {
super.onResume();
System.out.println("ON RESUME INCOMING CHECK");
if (share.getisFromTabsClearImage()) {
imageSetImageView.setImageDrawable(getResources().getDrawable(
R.drawable.ingenbildvald));
emailSendButton.setBackgroundDrawable(getResources().getDrawable(
R.drawable.skicka_button));
emailSendButton.setEnabled(false);
share.setisFromTabsClearImage(false);
}
if (isEmailSend) {
imageSetImageView.setImageDrawable(getResources().getDrawable(
R.drawable.ingenbildvald));
emailSendButton.setBackgroundDrawable(getResources().getDrawable(
R.drawable.skicka_button));
emailSendButton.setEnabled(false);
isEmailSend = false;
}
}

how to apply popup in bingmap pushpin

I have bing map controll in which so many maplayer are there
I want to display popup in my pushpin click event same like this
Bing Maps Gets New Look for Pushpins, Popups, And Transit - See more at: http://wmpoweruser.com/bing-maps-gets-new-look-for-pushpins-popups-and-transit/#sthash.ApL3q6bA.dpuf
How i can do this.
Give me some advice for developing popup in bing map controll and yes i want to show latitude,longlatitude and address in this popup
Mu pushin code
void _ClsGetDeviceMap_WorkFinished(bool success)
{
try
{
if (ClsGetDeviceMap.lstresponsecode.ElementAt<string>(0).Trim() == "1")
{
MessageBox.Show(ClsGetDeviceMap.lstresponsemsg.ElementAt<string>(0));
for (int i = 0; i <= ClsGetDeviceMap.lstLongLatitude.Count - 1; i++)
{
string lat, lon;
lat = ClsGetDeviceMap.lstLatitude.ElementAt<string>(i).Trim();
lon = ClsGetDeviceMap.lstLongLatitude.ElementAt<string>(i).Trim();
Latitude = Convert.ToDouble(lat);
LongLatitude = Convert.ToDouble(lon);
GpsSpeed = 44.21811;
map1.Center = new GeoCoordinate(Latitude, LongLatitude, GpsSpeed);
map1.ZoomLevel = 17;
map1.ZoomBarVisibility = Visibility.Visible;
imglayer[i] = new MapLayer();
Image img = new Image();
img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/ReachMe;component/Images/mappinicn.png", UriKind.Relative));
img.Opacity = 0.8;
img.Stretch = System.Windows.Media.Stretch.None;
GeoCoordinate location = new GeoCoordinate() { Latitude = Latitude, Longitude = LongLatitude };
PositionOrigin position = PositionOrigin.Center;
imglayer[i].AddChild(img, location, position);
Pushpin pin = new Pushpin();
ToolTipService.SetToolTip(pin, "Pushpin 1\r\nThis is the first pushpin infobox.");
imglayer[i].Children.Add(pin);
map1.Children.Add(imglayer[i]);
myCoorditeWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
myCoorditeWatcher.MovementThreshold = 20;
var g1 = GestureService.GetGestureListener(imglayer[i]);
g1.Tap += new EventHandler<GestureEventArgs>(g1_Tap);
}
}
else// if error
{
MessageBox.Show("No Data Between This data");
// NavigationService.Navigate(new Uri("/ReachMeView/Login.xaml", UriKind.RelativeOrAbsolute));
}
}
catch (Exception ex)
{
Error.WriteErrorLog(ex.ToString(), "MainPage.xaml", "Data_WorkFinished");
}
}
void g1_Tap(object sender, GestureEventArgs e)
{
for (int i = 0; i <= ClsGetDeviceMap.lstLongLatitude.Count - 1; i++)
{
if (sender.Equals(imglayer[i]))
{
MessageBox.Show(ClsGetDeviceMap.lstLocationName.ElementAt<string>(i).Trim());
MessageBox.Show(ClsGetDeviceMap.lstLatitude.ElementAt<string>(i).Trim());
MessageBox.Show(ClsGetDeviceMap.lstLongLatitude.ElementAt<string>(i).Trim());
MessageBox.Show(ClsGetDeviceMap.lstDate.ElementAt<string>(i).Trim());
}
}
}

Resources