Skip to content

Instantly share code, notes, and snippets.

Created October 22, 2014 13:39
Show Gist options
  • Save anonymous/83a855d44d697235849b to your computer and use it in GitHub Desktop.
Save anonymous/83a855d44d697235849b to your computer and use it in GitHub Desktop.
// This file has been autogenerated from a class added in the UI designer.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using B2.Mobile.Common.iOS;
using BigTed;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Threading;
namespace B2.Mobile.Common.Ui.iOS.Controller
{
public class MediaCollectionViewController<THandler, TModel> : UICollectionViewController, IMediaCollectionViewController
where TModel : class, IMediaModel, new()
where THandler: CreateMediaDataHandler<TModel>
{
private readonly MediaCollectionDelegate<THandler, TModel> _delegate;
private readonly int _parentId;
private readonly THandler _dataHandler;
private readonly bool _showDescriptionButton;
private readonly bool _showBottomBarInsteadOfTop;
private readonly string _albumName;
private UIImagePickerControllerQualityType _videoQuality;
private UILongPressGestureRecognizer _longPressGestureRecognizer;
private UIImagePickerController _imagePicker;
private AudioRecordingOverlay _audioRecordingOverlay;
private AudioPlaybackOverlay _audioPlaybackOverlay;
private ImagePickerControllerDelegate _imagePickerDelegate;
private UIToolbar _toolbar;
private PopoverInputController _popover;
private CustomInputViewController _inputViewController;
private UIBarButtonItem _cameraItem;
private UIBarButtonItem _videoItem;
private UIBarButtonItem _audioItem;
public NSIndexPath DeleteIndexPath { get; set; }
private string AlbumName { get { return _albumName; } }
public string CurrentFullscreenPath { get; set; }
private bool _readOnly;
public bool ReadOnly {
get { return _readOnly; }
set
{
_readOnly = value;
_cameraItem.Enabled = !_readOnly;
_audioItem.Enabled = !_readOnly;
_videoItem.Enabled = !_readOnly;
}
}
public bool Landscape
{
get { return InterfaceOrientation == UIInterfaceOrientation.LandscapeLeft || InterfaceOrientation == UIInterfaceOrientation.LandscapeRight; }
}
public VideoQuality VideoQuality
{
set { _videoQuality = GetVideoQuality(value); }
}
public List<MediaItem> MediaAndDescriptions { get; set; }
public static UICollectionViewLayout GetLayout()
{
var imageLayout = new UICollectionViewFlowLayout
{
ScrollDirection = UICollectionViewScrollDirection.Vertical,
SectionInset = new UIEdgeInsets(10, 10, 50, 10),
MinimumInteritemSpacing = 10,
MinimumLineSpacing = 1
};
return imageLayout;
}
public MediaCollectionViewController (int parentId, THandler dataHandler, string albumName, bool showDescription, bool showBottomBarInsteadOfTop) : base (GetLayout())
{
_albumName = albumName;
_showDescriptionButton = showDescription;
_showBottomBarInsteadOfTop = showBottomBarInsteadOfTop;
_dataHandler = dataHandler;
_parentId = parentId;
_delegate = new MediaCollectionDelegate<THandler, TModel>(this);
// CollectionBehavior
InitializeCollectionView();
}
private UIImagePickerControllerQualityType GetVideoQuality(VideoQuality videoQuality)
{
switch (videoQuality)
{
case VideoQuality.High:
return UIImagePickerControllerQualityType.High;
case VideoQuality.Medium:
return UIImagePickerControllerQualityType.Medium;
case VideoQuality.Low:
return UIImagePickerControllerQualityType.Low;
default:
throw new ArgumentOutOfRangeException();
}
}
private void InitializeCollectionView()
{
CollectionView.Delegate = _delegate;
CollectionView.ScrollEnabled = true;
CollectionView.Bounces = true;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
CurrentFullscreenPath = null;
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// UI
CollectionView.BackgroundColor = UIColor.White;
// Kamera und andere Picker
_cameraItem = new UIBarButtonItem(UIBarButtonSystemItem.Camera, ButtonCameraClicked);
_videoItem = new UIBarButtonItem(UIImage.FromBundle("Images/film-7.png"), UIBarButtonItemStyle.Plain, ButtonVideoClicked);
_audioItem = new UIBarButtonItem(UIImage.FromBundle("Images/microphone-7.png"), UIBarButtonItemStyle.Plain, ButtonAudioClicked);
var spaceItem = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace) { Width = 20.0f };
// Prüfen ob eine Kamera vorhanden ist (z.B. Simulator)
if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
{
_cameraItem.Enabled = false;
_videoItem.Enabled = false;
}
if (!_showBottomBarInsteadOfTop && NavigationItem != null)
{
NavigationItem.RightBarButtonItem = _cameraItem;
}
else if (_showBottomBarInsteadOfTop)
{
var y = View.Frame.Height - 44;
_toolbar = new UIToolbar(new RectangleF(0, y, View.Frame.Width, 44));
_toolbar.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleWidth;
_toolbar.Translucent = false;
View.AddSubview(_toolbar);
_toolbar.Items = new[] { _cameraItem, spaceItem, _videoItem, spaceItem, _audioItem };
}
// Layout
EdgesForExtendedLayout = UIRectEdge.None;
// Cell Klasse registrieren
CollectionView.RegisterClassForCell (typeof(ImageDescriptionCell), new NSString("imagePortraitCell"));
CollectionView.RegisterClassForCell (typeof(ImageDescriptionCell), new NSString("imageLandscapeCell"));
// Gesten Registrieren
_longPressGestureRecognizer = new UILongPressGestureRecognizer(LongPressOnCell);
CollectionView.AddGestureRecognizer(_longPressGestureRecognizer);
// Datasource
MediaAndDescriptions = new List<MediaItem>();
// Bilder laden
LoadMediaAndDescriptions();
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
//LoadMediaAndDescriptions();
CollectionView.ReloadData();
}
private void LongPressOnCell(UIGestureRecognizer gestureRecognizer)
{
if (ReadOnly)
return;
if (gestureRecognizer.State != UIGestureRecognizerState.Began)
return;
DeleteIndexPath = CollectionView.IndexPathForItemAtPoint(gestureRecognizer.LocationInView(CollectionView));
if (DeleteIndexPath == null)
return;
var cell = CollectionView.CellForItem(DeleteIndexPath);
if (cell == null)
return;
cell.BecomeFirstResponder();
var deleteMenuItem = new UIMenuItem("Löschen", new MonoTouch.ObjCRuntime.Selector("deleteCellSelector"));
var menuController = UIMenuController.SharedMenuController;
menuController.MenuItems = new[] { deleteMenuItem };
menuController.SetTargetRect(cell.Frame, cell.Superview);
menuController.SetMenuVisible(true, true);
}
[Export("deleteCellSelector")]
public void DeleteCellSelector()
{
var selectedItem = MediaAndDescriptions[DeleteIndexPath.Row];
var model = _dataHandler.Get(i => i.ParentId == _parentId && i.Pfad == selectedItem.Pfad);
_dataHandler.Delete(model);
LoadMediaAndDescriptions();
}
public void ButtonCameraClicked(object sender, EventArgs eventArgs)
{
if (_imagePicker == null)
{
_imagePickerDelegate = new ImagePickerControllerDelegate(this);
_imagePicker = new UIImagePickerController();
_imagePicker.ImagePickerControllerDelegate = _imagePickerDelegate;
}
if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
_imagePicker.SourceType = UIImagePickerControllerSourceType.Camera;
else
_imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
PresentViewController(_imagePicker, true, () => { Thread.Sleep(2000); });
}
public void ButtonVideoClicked(object sender, EventArgs eventArgs)
{
if (!AudioHelper.IsAudioRecordingAvailable())
{
new UIAlertView("Audio", "Der Zugriff auf das Mikrofon wurde verweigert. Bitte in den Geräteeinstellungen zulassen, ansonsten enthält das Video keinen Ton", null, "Schliessen").Show();
// else if (UIDevice.CurrentDevice.IsiOS8())
// {
// var alert = new UIAlertView("Zugriff Verweigert", "Der Zugriff auf das Mikrofon wurde verweigert. Bitte in den Geräteeinstellungen zulassen", null, "Schliessen", "Einstellungen");
// alert.Clicked += (sender, e) =>
// {
// if (e.ButtonIndex == 1 && UIApplication.SharedApplication.CanOpenUrl(NSUrl.FromString(UIApplication.OpenSettingsUrlString)))
// {
//
// }
// };
// alert.Show();
// }
}
const UIImagePickerControllerSourceType cameraType = UIImagePickerControllerSourceType.Camera;
if(HasVideoSupport())
{
_imagePicker = new UIImagePickerController();
_imagePicker.SourceType = cameraType;
_imagePicker.MediaTypes = new []{"public.movie"} ;
_imagePicker.VideoQuality = _videoQuality;
_imagePicker.Delegate = new VideoImagePickerDelegate(this);
PresentViewController(_imagePicker, true, null);
}
else
{
using (var alert = new UIAlertView("Video", "Videoaufnahme wird nicht unterstützt.", null, "Schliessen", null))
{
alert.Show();
}
}
}
private bool HasVideoSupport()
{
var cameraType = UIImagePickerControllerSourceType.Camera;
var cameraSupport = UIImagePickerController.IsSourceTypeAvailable(cameraType);
return (cameraSupport) && UIImagePickerController.AvailableMediaTypes(cameraType).Contains("public.movie");
}
public void PlayAudio(string pfad)
{
_audioPlaybackOverlay = new AudioPlaybackOverlay(pfad, View.Bounds);
_audioPlaybackOverlay.AutoresizingMask = ~UIViewAutoresizing.None;
View.AddSubview(_audioPlaybackOverlay);
}
public void ButtonAudioClicked(object sender, EventArgs eventArgs)
{
if (!AudioHelper.IsAudioRecordingAvailable())
{
new UIAlertView("Zugriff Verweigert", "Der Zugriff auf das Mikrofon wurde verweigert. Bitte in den Geräteeinstellungen zulassen", null, "Schliessen").Show();
// else if (UIDevice.CurrentDevice.IsiOS8())
// {
// var alert = new UIAlertView("Zugriff Verweigert", "Der Zugriff auf das Mikrofon wurde verweigert. Bitte in den Geräteeinstellungen zulassen", null, "Schliessen", "Einstellungen");
// alert.Clicked += (sender, e) =>
// {
// if (e.ButtonIndex == 1 && UIApplication.SharedApplication.CanOpenUrl(NSUrl.FromString(UIApplication.OpenSettingsUrlString)))
// {
//
// }
// };
// alert.Show();
// }
return;
}
var filename = string.Format("{0}_{1}", _albumName, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss.aac"));
_audioRecordingOverlay = new AudioRecordingOverlay(filename, View.Bounds);
_audioRecordingOverlay.AutoresizingMask = ~UIViewAutoresizing.None;
_audioRecordingOverlay.ClosedAction = AudioRecordingClosed;
View.AddSubview(_audioRecordingOverlay);
}
private void AudioRecordingClosed(string path)
{
UIApplication.SharedApplication.IdleTimerDisabled = false;
if (string.IsNullOrWhiteSpace(path))
return;
BTProgressHUD.Show("Audio wird gespeichert...");
MediaSaved(path, MediaType.Audio);
}
private void MediaSaved(string assetUrl, MediaType mediaTyp)
{
BTProgressHUD.Dismiss();
if (assetUrl != null)
{
_dataHandler.CreateMediaModel(assetUrl, _parentId, mediaTyp);
LoadMediaAndDescriptions();
}
else
{
// Todo Show Error
}
}
private void LoadMediaAndDescriptions()
{
MediaAndDescriptions.Clear();
var medien = _dataHandler.GetAll(i => i.ParentId == _parentId);
foreach (var media in medien)
{
UIImage image = null;
if (media.MediaTyp == MediaType.Image || media.MediaTyp == MediaType.Video)
{
image = ImageHelper.GetImage(media.Pfad, true);
if (image == null)
{
_dataHandler.Delete(media);
continue;
}
}
else if (media.MediaTyp == MediaType.Audio)
{
image = UIImage.FromBundle("Images/audio.png");
if (!File.Exists(media.Pfad))
{
_dataHandler.Delete(media);
continue;
}
}
var mediaItem = new MediaItem { Id = media.Id, Beschreibung = media.Bezeichnung, Bild = image, MediaTyp = media.MediaTyp, Pfad = media.Pfad };
MediaAndDescriptions.Add(mediaItem);
}
CollectionView.ReloadData();
}
public override int NumberOfSections(UICollectionView collectionView)
{
return 1;
}
public override int GetItemsCount(UICollectionView collectionView, int section)
{
return MediaAndDescriptions.Count;
}
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
var cell = (Landscape)
? collectionView.DequeueReusableCell(new NSString("imageLandscapeCell"), indexPath) as ImageDescriptionCell
: collectionView.DequeueReusableCell(new NSString("imagePortraitCell"), indexPath) as ImageDescriptionCell; ;
//var cell = collectionView.DequeueReusableCell(new NSString("imageCell"), indexPath) as ImageDescriptionCell;
if (cell == null)
return new UICollectionViewCell();
var data = MediaAndDescriptions[indexPath.Row];
cell.ShowMediaDescriptionButton = _showDescriptionButton;
cell.MediaItem = data;
cell.Image = data.Bild;
cell.Icon = GetMediaIcon(data.MediaTyp);
cell.ReadOnly = ReadOnly;
cell.Controller = this;
cell.HasDescription = !string.IsNullOrWhiteSpace(data.Beschreibung);
return cell;
}
private UIImage GetMediaIcon(MediaType mediaType)
{
switch (mediaType)
{
case MediaType.Image:
return UIImage.FromBundle("Images/camera-7.png");
case MediaType.Video:
return UIImage.FromBundle("Images/film-7.png");
case MediaType.Audio:
return UIImage.FromBundle("Images/microphone-7.png");
default:
throw new ArgumentOutOfRangeException();
}
}
public void SaveDescriptionAction(string description)
{
if (string.IsNullOrWhiteSpace(CurrentFullscreenPath))
return;
var model = _dataHandler.Get(i => i.ParentId == _parentId && i.Pfad == CurrentFullscreenPath);
if (model == null)
return;
model.Version = DateTime.Now;
model.Bezeichnung = description;
_dataHandler.InsertOrUpdate(model);
_dataHandler.UpdateParentVersion(_parentId);
LoadMediaAndDescriptions();
}
public class ImagePickerControllerDelegate : UIImagePickerControllerDelegate
{
private readonly MediaCollectionViewController<THandler, TModel> _controller;
public ImagePickerControllerDelegate(MediaCollectionViewController<THandler, TModel> controller)
{
_controller = controller;
}
public override void Canceled(UIImagePickerController picker)
{
picker.DismissViewController(true, null);
}
public override void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info)
{
BTProgressHUD.Show("Bild wird gespeichert...");
var image = (UIImage)info.ObjectForKey(new NSString("UIImagePickerControllerOriginalImage"));
image.SaveToCustomPhotosAlbum(info[UIImagePickerController.MediaMetadata] as NSDictionary, _controller.AlbumName, _controller.MediaSaved);
picker.DismissViewController(true, null);
}
}
public class VideoImagePickerDelegate : UIImagePickerControllerDelegate
{
MediaCollectionViewController<THandler, TModel> _controller;
public VideoImagePickerDelegate(MediaCollectionViewController<THandler, TModel> controller)
{
_controller = controller;
}
public override void Canceled (UIImagePickerController picker)
{
picker.DismissViewController(true, null);
}
public override void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info)
{
var mediaUrlKey = new NSString("UIImagePickerControllerMediaURL");
var mediaPath = (NSUrl) info.ObjectForKey(mediaUrlKey);
if(mediaPath != null)
{
if(UIVideo.IsCompatibleWithSavedPhotosAlbum(mediaPath.Path))
{
BTProgressHUD.Show("Video wird gespeichert...");
VideoHelper.SaveToCustomPhotosAlbum(mediaPath, _controller.AlbumName, _controller.MediaSaved);
}
else
{
using (var alert = new UIAlertView("Video", "Video konnte nicht gespeichert werden", null, "Schliessen", null))
{
alert.Show();
}
}
}
_controller.DismissViewController(true, null);
}
}
public void ShowDescription(MediaItem mediaItem, UICollectionViewCell cell)
{
var textField = new MultiLineTextField();
textField.AutoresizingMask = ~UIViewAutoresizing.None;
textField.Text = mediaItem.Beschreibung;
textField.ReadOnly = ReadOnly;
textField.Bounces = false;
textField.AutocapitalizationType = UITextAutocapitalizationType.Sentences;
var imageDescriptionCell = (ImageDescriptionCell)cell;
if (UIDevice.CurrentDevice.ModelHardware() == IOSHardware.iPad)
{
// In einem Popover anzeigen
_popover = PopoverInputController.GetPopoverController(textField, "Beschreibung", () => ClosedDescription(imageDescriptionCell), null, imageDescriptionCell.ReadOnly);
_popover.PopoverContentSize = new SizeF(400, 400);
_popover.ShowNavigationBar = true;
_popover.PresentFromRect(cell.Bounds, cell, UIPopoverArrowDirection.Any, true);
}
else // Bei unbekannten oder iPhone / iPod immer Model anzeigen
{
_inputViewController = CustomInputViewController.GetController(textField, "Beschreibung", () => ClosedDescription(imageDescriptionCell));
// In einem neuen Navigation-Dialog anzeigen
if (NavigationController != null)
NavigationController.PushViewController(_inputViewController, true);
else
new UIAlertView("Beschreibung", "Beschreibung konnte nicht angezeigt werden, weil kein NavigationController vorliegt", null, "Schliessen", null).Show();
}
}
private void ClosedDescription(ImageDescriptionCell cell)
{
if (_popover != null && _popover.Canceled)
return;
MultiLineTextField textField = null;
if (_popover != null && _popover.View != null)
textField = _popover.View as MultiLineTextField;
else if (_inputViewController != null && _inputViewController.View != null)
textField = _inputViewController.InputView as MultiLineTextField;
if (textField == null)
return;
cell.MediaItem.Beschreibung = textField.Text;
var mediaModel = _dataHandler.Get(cell.MediaItem.Id);
mediaModel.Bezeichnung = cell.MediaItem.Beschreibung;
_dataHandler.InsertOrUpdate(mediaModel);
CollectionView.ReloadData();
}
}
public class MediaItem
{
public string Beschreibung {get;set;}
public string Pfad {get;set;}
public UIImage Bild { get; set; }
public MediaType MediaTyp {get;set;}
public int Id { get; set; }
}
public class MediaCollectionDelegate<THandler, TModel> : UICollectionViewDelegateFlowLayout
where TModel : class, IMediaModel, new()
where THandler: CreateMediaDataHandler<TModel>
{
private readonly MediaCollectionViewController<THandler, TModel> _controller;
public MediaCollectionDelegate(MediaCollectionViewController<THandler, TModel> controller)
{
_controller = controller;
}
public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
{
var mediaItem = _controller.MediaAndDescriptions[indexPath.Row];
_controller.DeleteIndexPath = indexPath;
_controller.CurrentFullscreenPath = mediaItem.Pfad;
if (mediaItem.MediaTyp == MediaType.Image)
{
var fullScreenImage = ImageHelper.GetImage(_controller.CurrentFullscreenPath, false);
var fullScreenImageViewController = new FullScreenImageViewController
{
Image = fullScreenImage,
Text = _controller.MediaAndDescriptions[indexPath.Row].Beschreibung,
SaveDescriptionAction = _controller.SaveDescriptionAction,
DeleteAction = DeleteSelectedMedia,
ReadOnly = _controller.ReadOnly
};
_controller.NavigationController.PushViewController(fullScreenImageViewController, true);
}
else if (mediaItem.MediaTyp == MediaType.Video)
{
var fullScreenVideoController = new FullScreenVideoViewController(new NSUrl(mediaItem.Pfad)) {ReadOnly = _controller.ReadOnly};
fullScreenVideoController.DeleteAction = DeleteSelectedMedia;
_controller.NavigationController.PushViewController(fullScreenVideoController, true);
}
else if (mediaItem.MediaTyp == MediaType.Audio)
{
_controller.PlayAudio(mediaItem.Pfad);
}
}
private void DeleteSelectedMedia()
{
_controller.DeleteCellSelector();
}
public override SizeF GetSizeForItem(UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath)
{
float x;
if (UIDevice.CurrentDevice.ModelHardware() == IOSHardware.iPad)
{
if (_controller.Landscape)
{
x = collectionView.Bounds.Width / 6;
}
else
{
x = collectionView.Bounds.Width / 5;
}
}
else
{
if (_controller.Landscape)
{
x = collectionView.Bounds.Width / 4;
}
else
{
x = collectionView.Bounds.Width / 3;
}
}
return new SizeF(x, x+40);
}
}
public class ImageDescriptionCell : UICollectionViewCell
{
private UIButton _iconView;
private UIButton _descriptionIconView;
private UIImageView _imageView;
private bool _hasDescription;
//private UILabel _textLabel;
[Export ("initWithFrame:")]
public ImageDescriptionCell (RectangleF frame) : base (new RectangleF(frame.X, frame.Y, frame.Width, frame.Height))
{
InitializeUi();
}
private void InitializeUi()
{
BackgroundColor = UIColor.Clear;
// Image
//var imageBounds = new RectangleF(0, 0, ContentView.Bounds.Width, ContentView.Bounds.Height);
_imageView = new UIImageView(new RectangleF(Bounds.X, Bounds.Y, Bounds.Width, Bounds.Height - 40));
//_imageView.BackgroundColor = UIColor.Green;
_imageView.AutoresizingMask = ~UIViewAutoresizing.None;
//_imageView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleBottomMargin;
_imageView.ContentMode = UIViewContentMode.ScaleAspectFit;
ContentView.AddSubview(_imageView);
// Beschreibung
//var labelHeight = UIFont.SystemFontOfSize(UIFont.SystemFontSize).LineHeight + 10;
//var textBounds = new RectangleF(10, ContentView.Bounds.Height - (labelHeight + 10), ContentView.Bounds.Width - 20, labelHeight);
//_textLabel = new UILabel(textBounds);
//_textLabel.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin;
//_textLabel.TextAlignment = UITextAlignment.Center;
//_textLabel.BackgroundColor = UIColor.FromRGBA(255, 255, 255, 220);
//_textLabel.Layer.CornerRadius = 5.0f;
//_textLabel.TextColor = UIColor.FromRGBA(0, 0, 0, 127);
//_textLabel.Font = UIFont.ItalicSystemFontOfSize(UIFont.SystemFontSize);
//ContentView.AddSubview(_textLabel);
// Icon Button
var iconFrame = new RectangleF(0, 0, 32, 32);
_iconView = new UIButton(UIButtonType.RoundedRect);
_iconView.Frame = iconFrame;
_iconView.AutoresizingMask = UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleBottomMargin;
_iconView.ContentMode = UIViewContentMode.ScaleAspectFit;
_iconView.BackgroundColor = UIColor.FromRGBA(255, 255, 255, 191);
_iconView.Layer.CornerRadius = 5.0f;
ContentView.AddSubview(_iconView);
// Media description button
//var descriptionIconFrame = new RectangleF(ContentView.Bounds.Width - 5 - 32, ContentView.Bounds.Height - 5 - 32, 32, 32);
var descriptionIconFrame = new RectangleF(5, Bounds.Height - 5 - 32, Bounds.Width - 10, 32);
_descriptionIconView = new UIButton(UIButtonType.RoundedRect);
_descriptionIconView.Frame = descriptionIconFrame;
_descriptionIconView.AutoresizingMask = UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleBottomMargin;
_descriptionIconView.ContentMode = UIViewContentMode.ScaleAspectFit;
_descriptionIconView.Layer.CornerRadius = 5.0f;
if (UIDevice.CurrentDevice.ModelHardware() == IOSHardware.iPad)
_descriptionIconView.SetTitle("Beschreibung", UIControlState.Normal);
_descriptionIconView.ImageEdgeInsets = new UIEdgeInsets(0, 0, 0, 10);
_descriptionIconView.TitleEdgeInsets = new UIEdgeInsets(0, 10, 0, 0);
_descriptionIconView.TouchUpInside += ShowDescription;
ContentView.AddSubview(_descriptionIconView);
}
private PointF GetIconPoint(SizeF size)
{
if (size.Height > size.Width)
{
// Portrait
var frameBorder = (ContentView.Frame.Width - (size.Width / (size.Height / ContentView.Frame.Height))) / 2;
var x = frameBorder + 5 + 16;
var y = 5;
return new PointF(x, y);
}
else
{
// Portrait
var x = 5;
var frameBorder = (ContentView.Frame.Height - (size.Height / (size.Width / ContentView.Frame.Width))) / 2;
var y = frameBorder + 5 - 16;
return new PointF(x, y);
}
}
private void ShowDescription(object sender, EventArgs e)
{
Controller.ShowDescription(MediaItem, this);
}
public bool HasDescription
{
get { return _hasDescription; }
set
{
_hasDescription = value;
var icon = (_hasDescription) ? UIImage.FromBundle("Images/document-7.png") : UIImage.FromBundle("Images/document-empty-7.png");
_descriptionIconView.SetImage(icon, UIControlState.Normal);
}
}
public IMediaCollectionViewController Controller { get; set; }
public override bool CanBecomeFirstResponder
{
get
{
return true;
}
}
public UIImage Image
{
set
{
if (_imageView != null)
{
if (value != null)
{
//var image = value.Scale(new SizeF(Bounds.Width, Bounds.Height));
_imageView.Image = value;
var point = GetIconPoint(value.Size);
_iconView.Frame = new RectangleF(point, new SizeF(32, 32));
}
}
}
}
public bool ReadOnly { get; set; }
public MediaItem MediaItem { get; set; }
public bool ShowMediaDescriptionButton { get; set; }
public UIImage Icon
{
set
{
_iconView.SetImage(value, UIControlState.Normal);
}
}
}
public interface IMediaCollectionViewController
{
void ShowDescription(MediaItem mediaItem, UICollectionViewCell cell);
}
}
@zhm
Copy link

zhm commented Oct 27, 2014

I saw this in StackExchange but can't comment yet.

http://stackoverflow.com/questions/26508857/uiimagepickercontroller-show-black-screen-for-every-second-shot

I'm experiencing this same exact issue (iOS 8.1 on iPhone 6). Even a dead simple test app does it. The built-in Messages app also has the same behavior. Open Messages and take a picture inside the app to send to someone. Then immediately take another one. I'm seeing a black screen, and sometimes even the previous photo I took instead of the live preview! Also of note, I'm only able to reproduce the problem on my iPhone 6. My iPhone 5s doesn't seem to have the same behavior.

@zakariaTas
Copy link

Did you find a solution for your problem ? indeed i have an app which launch the camera. On iphone 6 version 8.1.2, i have users reporting that when taking a photo, the first one is ok but when trying the second time, they get a black screen, they recover once they restart the app but fall in the same situation when taking again a second photo. What's strange is that other users did not report the issue with same iphone and test condition ! i am launching the camera from a tool bar button (bottom).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment