我使用了以下代码,但它无效。
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using XLabs.Platform.Device;
using XLabs.Platform.Services.Media;
namespace CalbrenEnterprises.Pages
{
public class TestPage : ContentPage
{
private ImageSource imageSource;
private IMediaPicker mediaPicker;
private Image img;
private string status;
public TestPage()
{
this.Title = "Camera Test";
NavigationPage.SetHasNavigationBar(this, false);
img = new Image() { HeightRequest = 300, WidthRequest = 300, BackgroundColor = Color.FromHex("#D6D6D2"), Aspect = Aspect.AspectFit };
var addPictureButton = new Button()
{
Text = "Select Picture",
Command = new Command(async () => { await SelectPicture(); })
};
StackLayout stack = new StackLayout();
stack.VerticalOptions = LayoutOptions.FillAndExpand;
stack.Children.Add(new BoxView { Color = Color.Transparent, HeightRequest = 20 });
stack.Children.Add(addPictureButton);
stack.Children.Add(img);
ScrollView scrollview = new ScrollView
{
Orientation = ScrollOrientation.Vertical,
VerticalOptions = LayoutOptions.FillAndExpand,
Content = stack
};
this.Content = new StackLayout
{
Children = { scrollview }
};
}
private async Task SelectPicture()
{
mediaPicker = DependencyService.Get<IMediaPicker>();
imageSource = null;
try
{
var mediaFile = await mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
imageSource = ImageSource.FromStream(() => mediaFile.Source);
img.Source = imageSource;
}
catch (System.Exception ex)
{
this.status = ex.Message;
}
}
}
}
问题:
如何从画廊中选择照片并在Xamarin.forms中的PCL项目中从相机拍摄照片?
答案 0 :(得分:1)
var device = Resolver.Resolve<IDevice>();
mediaPicker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;
if (mediaPicker == null) throw new NullReferenceException("MediaPicker DependencyService.Get error");
try
{
if (mediaPicker.IsCameraAvailable)
{
var options = new CameraMediaStorageOptions() {
DefaultCamera = CameraDevice.Front,
SaveMediaOnCapture = true,
Directory = "YourAppName",
Name = string.Format("YourAppName_{0}", DateTime.Now.ToString("yyMMddhhmmss")),
MaxPixelDimension = 1024,
PercentQuality = 85
};
var mediaFile = await mediaPicker.TakePhotoAsync(options);
if (mediaFile != null && mediaFile.Source != null)
{
// do something with your photo
}
}
else
{
Logger.Info("Camera not available");
}
}
catch (TaskCanceledException)
{
Logger.Info("TakePhoto cancelled");
}
catch (Exception ex)
{
Logger.Error(ex);
}