Created
February 19, 2017 21:18
-
-
Save mattwhetton/aeb070bd0eabe5b0ea6f52b7550008a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Globalization; | |
using Android.Graphics; | |
using Android.Graphics.Drawables; | |
using Cirrious.CrossCore.Converters; | |
using DecisionBuddy.Controls; | |
using DecisionBuddy.Controls.Utils; | |
using DecisionBuddy.Core.Model; | |
namespace DecisionBuddy.UI.Droid.Converters | |
{ | |
public class ContactImageConverter : MvxValueConverter<Contact, Bitmap> | |
{ | |
private const int DEFAULT_SIZE = 50; | |
protected override Bitmap Convert(Contact value, Type targetType, object parameter, CultureInfo culture) | |
{ | |
if(value == null) return null; | |
if (value.Thumbnail != null && value.Thumbnail.Length > 0) | |
{ | |
return BitmapFactory.DecodeByteArray(value.Thumbnail, 0, value.Thumbnail.Length); | |
} | |
var size = DEFAULT_SIZE; | |
if (parameter is long || parameter is int) | |
size = System.Convert.ToInt32(parameter); | |
var canvas = new Canvas(); | |
var letter = value.Name.Trim().Substring(0,1); | |
var textDrawable = TextDrawable | |
.Builder() | |
.BeginConfig() | |
.SetHeight(size) | |
.SetWidth(size) | |
.EndConfig() | |
.BuildRound(letter, ColorGenerator.Material.GetColor(letter)); | |
return DrawableToBitmap(textDrawable); | |
} | |
protected override Contact ConvertBack(Bitmap value, Type targetType, object parameter, CultureInfo culture) | |
{ | |
//var stream = new MemoryStream(); | |
//value.Compress(Bitmap.CompressFormat.Jpeg, 100, stream); | |
//return stream.ToArray(); | |
return null; | |
} | |
public static Bitmap DrawableToBitmap(Drawable drawable) | |
{ | |
Bitmap bitmap = null; | |
var bitmapDrawable = drawable as BitmapDrawable; | |
if (bitmapDrawable?.Bitmap != null) | |
{ | |
return bitmapDrawable.Bitmap; | |
} | |
if (drawable.IntrinsicWidth <= 0 || drawable.IntrinsicHeight <= 0) | |
{ | |
bitmap = Bitmap.CreateBitmap(1, 1, Bitmap.Config.Argb8888); // Single color bitmap will be created of 1x1 pixel | |
} | |
else | |
{ | |
bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth, drawable.IntrinsicHeight, Bitmap.Config.Argb8888); | |
} | |
var canvas = new Canvas(bitmap); | |
drawable.SetBounds(0, 0, canvas.Width, canvas.Height); | |
drawable.Draw(canvas); | |
return bitmap; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment