public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { var asset = (PHAsset)FetchResult [indexPath.Item]; // Dequeue an GridViewCell. var cell = (GridViewCell)collectionView.DequeueReusableCell(cellReuseIdentifier, indexPath); #if __IOS__ && !__TVOS__ // Add a badge to the cell if the PHAsset represents a Live Photo. // Add Badge Image to the cell to denote that the asset is a Live Photo. if (asset.MediaSubtypes.HasFlag(PHAssetMediaSubtype.PhotoLive)) { cell.LivePhotoBadgeImage = PHLivePhotoView.GetLivePhotoBadgeImage(PHLivePhotoBadgeOptions.OverContent); } #endif // Request an image for the asset from the PHCachingImageManager. cell.RepresentedAssetIdentifier = asset.LocalIdentifier; imageManager.RequestImageForAsset(asset, thumbnailSize, PHImageContentMode.AspectFill, null, (image, info) => { // Set the cell's thumbnail image if it's still showing the same asset. if (cell.RepresentedAssetIdentifier == asset.LocalIdentifier) { cell.ThumbnailImage = image; } }); return(cell); }
/// <inheritdoc /> public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { var cell = collectionView.DequeueReusableCell(AlbumViewCell.Key, indexPath) as AlbumViewCell ?? new AlbumViewCell(); if (_imageManager == null) { return(cell); } if (cell.Tag != 0) { _imageManager.CancelImageRequest((int)cell.Tag); } var asset = AllAssets[(int)indexPath.Item]; cell.IsVideo = asset.MediaType == PHAssetMediaType.Video; cell.Duration = asset.Duration; cell.Tag = _imageManager.RequestImageForAsset(asset, _cellSize, PHImageContentMode.AspectFit, null, (result, info) => SetImageCellImage(cell, result)); return(cell); }
public override void WillAnimateRotation(UIInterfaceOrientation toInterfaceOrientation, double duration) { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { return; } var layout = CollectionViewFlowLayoutForOrientation(toInterfaceOrientation, _picker); //Update the AssetGridThumbnailSize: var scale = UIScreen.MainScreen.Scale; AssetGridThumbnailSize = new CGSize(layout.ItemSize.Width * scale, layout.ItemSize.Height * scale); ResetCachedAssets(); var options = new PHImageRequestOptions { Synchronous = false, NetworkAccessAllowed = true, DeliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic, ResizeMode = PHImageRequestOptionsResizeMode.Fast }; //This is optional. Reload visible thumbnails: foreach (var cell in CollectionView.VisibleCells) { var typedCell = (GMGridViewCell)cell; var currentTag = cell.Tag; _imageManager.RequestImageForAsset(typedCell.Asset, AssetGridThumbnailSize, PHImageContentMode.AspectFill, options, (image, info) => { // Only update the thumbnail if the cell tag hasn't changed. Otherwise, the cell has been re-used. if (cell.Tag == currentTag && typedCell.ImageView != null && image != null) { typedCell.ImageView.Image = image; } }); } CollectionView.SetCollectionViewLayout(layout, true); }
public override void ViewDidLoad() { base.ViewDidLoad (); PHPhotoLibrary.RequestAuthorization ((status) => { if(status == PHAuthorizationStatus.Authorized) { var result = PHAssetCollection.FetchTopLevelUserCollections(null); var assetCollection = result.firstObject as PHAssetCollection; var imageManager = new PHCachingImageManager(); var assets = PHAsset.FetchAssets(assetCollection, null); var imageAsset = assets[6]; this.InvokeOnMainThread(() => { imageManager.RequestImageForAsset((PHAsset)imageAsset, this.View.Frame.Size, PHImageContentMode.Default, null, new PHImageResultHandler(this.ImageReceived)); }); } }); }
public override void ViewDidLoad() { base.ViewDidLoad(); PHPhotoLibrary.RequestAuthorization((status) => { if (status == PHAuthorizationStatus.Authorized) { var result = PHAssetCollection.FetchTopLevelUserCollections(null); var assetCollection = result.firstObject as PHAssetCollection; var imageManager = new PHCachingImageManager(); var assets = PHAsset.FetchAssets(assetCollection, null); var imageAsset = assets[6]; this.InvokeOnMainThread(() => { imageManager.RequestImageForAsset((PHAsset)imageAsset, this.View.Frame.Size, PHImageContentMode.Default, null, new PHImageResultHandler(this.ImageReceived)); }); } }); }
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = (GMAlbumsViewCell)tableView.DequeueReusableCell(CellReuseIdentifier); if (cell == null) { cell = new GMAlbumsViewCell(UITableViewCellStyle.Subtitle, CellReuseIdentifier); cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; } // Increment the cell's tag var currentTag = cell.Tag + 1; cell.Tag = currentTag; // Set the label cell.TextLabel.Font = FontParser.GetFont(_picker.PickerFontName, _picker.PickerFontHeaderSize); cell.TextLabel.Text = _collectionsFetchResultsTitles[indexPath.Section][indexPath.Row]; cell.TextLabel.TextColor = _picker.PickerTextColor; // Retrieve the pre-fetched assets for this album: var assetsFetchResult = _collectionsFetchResultsAssets[indexPath.Section][indexPath.Row]; // Display the number of assets if (_picker.DisplayAlbumsNumberOfAssets) { cell.DetailTextLabel.Font = FontParser.GetFont(_picker.PickerFontName, _picker.PickerFontNormalSize); // Just use the number of assets. Album app does this: cell.DetailTextLabel.Text = string.Format("{0:0}", assetsFetchResult.Count); cell.DetailTextLabel.TextColor = _picker.PickerTextColor; } var numberOfAssets = assetsFetchResult.Count; // Set the 3 images (if exists): if (numberOfAssets > 0) { var scale = UIScreen.MainScreen.Scale; var options = new PHImageRequestOptions { Synchronous = false, NetworkAccessAllowed = true, DeliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic, ResizeMode = PHImageRequestOptionsResizeMode.Fast }; // Compute the thumbnail pixel size: var tableCellThumbnailSize1 = new CGSize(AlbumThumbnailSize1.Width * scale, AlbumThumbnailSize1.Height * scale); var asset = (PHAsset)assetsFetchResult[_picker.GridSortOrder == SortOrder.Ascending ? numberOfAssets - 1 : 0]; cell.SetVideoLayout(asset.MediaType == PHAssetMediaType.Video); _imageManager.RequestImageForAsset(asset, tableCellThumbnailSize1, PHImageContentMode.AspectFill, options, (image, info) => { if (cell.Tag == currentTag && cell.ImageView1 != null && image != null) { cell.ImageView1.Image = image; } }); // Second & third images: // TODO: Only preload the 3pixels height visible frame! if (numberOfAssets > 1) { // Compute the thumbnail pixel size: var tableCellThumbnailSize2 = new CGSize(AlbumThumbnailSize2.Width * scale, AlbumThumbnailSize2.Height * 2); asset = (PHAsset)assetsFetchResult[_picker.GridSortOrder == SortOrder.Ascending ? numberOfAssets - 2 : 1]; _imageManager.RequestImageForAsset(asset, tableCellThumbnailSize2, PHImageContentMode.AspectFill, options, (image, info) => { if (cell.Tag == currentTag && cell.ImageView2 != null && image != null) { cell.ImageView2.Image = image; } }); } else { cell.ImageView2.Image = null; } if (numberOfAssets > 2) { // Compute the thumbnail pixel size: var tableCellThumbnailSize3 = new CGSize(AlbumThumbnailSize3.Width * scale, AlbumThumbnailSize3.Height * 2); asset = (PHAsset)assetsFetchResult[_picker.GridSortOrder == SortOrder.Ascending ? numberOfAssets - 3 : 2]; _imageManager.RequestImageForAsset(asset, tableCellThumbnailSize3, PHImageContentMode.AspectFill, options, (image, info) => { if (cell.Tag == currentTag && cell.ImageView3 != null && image != null) { cell.ImageView3.Image = image; } }); } else { cell.ImageView3.Image = null; } } else { cell.SetVideoLayout(false); var emptyFolder = UIImage.FromFile("GMEmptyFolder"); cell.ImageView3.Image = emptyFolder; cell.ImageView2.Image = emptyFolder; cell.ImageView1.Image = emptyFolder; } return(cell); }
async Task <IList <MediaAsset> > LoadMediaAsync() { IList <MediaAsset> assets = new List <MediaAsset>(); var imageManager = new PHCachingImageManager(); var hasPermission = await RequestPermissionAsync(); if (hasPermission) { await Task.Run(async() => { var thumbnailRequestOptions = new PHImageRequestOptions(); thumbnailRequestOptions.ResizeMode = PHImageRequestOptionsResizeMode.Fast; thumbnailRequestOptions.DeliveryMode = PHImageRequestOptionsDeliveryMode.FastFormat; thumbnailRequestOptions.NetworkAccessAllowed = true; thumbnailRequestOptions.Synchronous = true; var requestOptions = new PHImageRequestOptions(); requestOptions.ResizeMode = PHImageRequestOptionsResizeMode.Exact; requestOptions.DeliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat; requestOptions.NetworkAccessAllowed = true; requestOptions.Synchronous = true; var fetchOptions = new PHFetchOptions(); fetchOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) }; fetchOptions.Predicate = NSPredicate.FromFormat($"mediaType == {(int)PHAssetMediaType.Image} || mediaType == {(int)PHAssetMediaType.Video}"); var fetchResults = PHAsset.FetchAssets(fetchOptions); var tmpPath = Path.GetTempPath(); var allAssets = fetchResults.Select(p => p as PHAsset).ToArray(); var thumbnailSize = new CGSize(300.0f, 300.0f); imageManager.StartCaching(allAssets, thumbnailSize, PHImageContentMode.AspectFit, thumbnailRequestOptions); imageManager.StartCaching(allAssets, PHImageManager.MaximumSize, PHImageContentMode.AspectFit, requestOptions); foreach (var result in fetchResults) { var phAsset = (result as PHAsset); var name = PHAssetResource.GetAssetResources(phAsset)?.FirstOrDefault()?.OriginalFilename; var asset = new MediaAsset() { Id = phAsset.LocalIdentifier, Name = name, Type = phAsset.MediaType == PHAssetMediaType.Image ? MediaAssetType.Image : MediaAssetType.Video, }; imageManager.RequestImageForAsset(phAsset, thumbnailSize, PHImageContentMode.AspectFit, thumbnailRequestOptions, (image, info) => { if (image != null) { NSData imageData = null; if (image.CGImage.RenderingIntent == CGColorRenderingIntent.Default) { imageData = image.AsJPEG(0.8f); } else { imageData = image.AsPNG(); } if (imageData != null) { var fileName = Path.Combine(tmpPath, $"tmp_thumbnail_{Path.GetFileNameWithoutExtension(name)}.jpg"); NSError error = null; imageData.Save(fileName, true, out error); if (error == null) { asset.PreviewPath = fileName; } } } }); switch (phAsset.MediaType) { case PHAssetMediaType.Image: imageManager.RequestImageForAsset(phAsset, PHImageManager.MaximumSize, PHImageContentMode.AspectFit, requestOptions, (image, info) => { if (image != null) { NSData imageData = null; if (image.CGImage.RenderingIntent == CGColorRenderingIntent.Default) { imageData = image.AsJPEG(0.8f); } else { imageData = image.AsPNG(); } if (imageData != null) { var fileName = Path.Combine(tmpPath, $"tmp_{name}"); NSError error = null; imageData.Save(fileName, true, out error); if (error == null) { asset.Path = fileName; } } } }); break; case PHAssetMediaType.Video: var videoRequestOptions = new PHVideoRequestOptions(); videoRequestOptions.NetworkAccessAllowed = true; var tcs = new TaskCompletionSource <bool>(); imageManager.RequestAvAsset(phAsset, null, (vAsset, audioMix, info) => { var avAsset = vAsset as AVUrlAsset; var avData = NSData.FromUrl(avAsset.Url); NSError error = null; var path = Path.Combine(tmpPath, $"tmp_{name}"); avData.Save(path, true, out error); if (error == null) { asset.Path = path; tcs.TrySetResult(true); } else { tcs.TrySetResult(false); } }); await tcs.Task; break; } UIApplication.SharedApplication.InvokeOnMainThread(delegate { OnMediaAssetLoaded?.Invoke(this, new MediaEventArgs(asset)); }); assets.Add(asset); if (requestStop) { break; } } }); imageManager.StopCaching(); } return(assets); }