Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Xamarin Blueprints

You're reading from   Xamarin Blueprints Leverage the power of Xamarin to create stunning cross-platform and native apps

Arrow left icon
Product type Paperback
Published in Sep 2016
Publisher Packt
ISBN-13 9781785887444
Length 516 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Michael Williams Michael Williams
Author Profile Icon Michael Williams
Michael Williams
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

Preface 1. Building a Gallery Application FREE CHAPTER 2. Building a SpeechTalk Application 3. Building a GPS Locator Application 4. Building an Audio Player Application 5. Building a Stocklist Application 6. Building a Chat Application 7. Building a File Storage Application 8. Building a Camera Application

Bitmap functions

What about the byte data? First, let's implement our BitmapHelpers; these will include two global functions to help with bitmap processing:

public static int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) 
        { 
            // Raw height and width of image 
            float height = options.OutHeight; 
            float width = options.OutWidth; 
            double inSampleSize = 1D; 
 
            if (height > reqHeight || width > reqWidth) 
            { 
                int halfHeight = (int)(height / 2); 
                int halfWidth = (int)(width / 2); 
 
                // Calculate a inSampleSize that is a power of 2 - the decoder will use a value that is a power of two anyway. 
                while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) 
                { 
                    inSampleSize *= 2; 
                } 
            } 
 
            return (int)inSampleSize; 
        } 
 
        public static async void CreateBitmap(ImageView imageView, byte[] imageData) 
        { 
            try 
            { 
                if (imageData != null)  
                { 
                    var bm = await BitmapFactory.DecodeByteArrayAsync(imageData, 0, imageData.Length); 
                    if (bm != null)  
                    { 
                        imageView.SetImageBitmap(bm); 
                    } 
                } 
            } 
            catch (Exception e)  
            { 
                Console.WriteLine ("Bitmap creation failed: " + e); 
            } 
        } 

Our first function will determine the best sample size by the requested width and height. This is a very good technique for reducing the resources required to load an image into memory. Our next function is used to create a bitmap for the ImageView that is passed in from the byte data.

The next step is to create this image data using the private method createCompressedImageDataFromBitmap:

private static byte[] createCompressedImageDataFromBitmap(string url) 
        { 
            BitmapFactory.Options options = new BitmapFactory.Options (); 
            options.InJustDecodeBounds = true; 
            BitmapFactory.DecodeFile (url, options); 
            options.InSampleSize = BitmapHelpers.CalculateInSampleSize (options, 1600, 1200); 
            options.InJustDecodeBounds = false; 
 
            Bitmap bm = BitmapFactory.DecodeFile (url, options); 
 
            var stream = new MemoryStream (); 
            bm.Compress (Bitmap.CompressFormat.Jpeg, 80, stream); 
            return stream.ToArray (); 
        } 

This method will take the image URI and decode the bitmap options in order to sample the smallest possible size for the dimensions provided.

We have to make sure that we flag InJustDecodeBounds so this bitmap is not loaded into memory while we are retrieving the options information. This approach is very useful for reducing images to the size we require, thus saving memory. We then compress the image by 80% into a JPEG and convert the stream into a byte array for our GalleryItem model.

Now let's go back to the adapter class and add this method to fill in the items of our ListAdapter:

public ListAdapter(Activity context) : base() 
        { 
            _context = context; 
            _items = new List<GalleryItem>(); 
 
            foreach (var galleryitem in ImageHandler.GetFiles (_context)) 
            { 
                _items.Add (galleryitem); 
            } 
        } 

Note

Remember we must have a reference in our list adapter to the main context.

Now for the final piece of the puzzle, connecting the adapter to our list view. Open up the MainActivity.cs file and update the code list like so:

public class MainActivity : Activity 
    { 
        private ListAdapter _adapter; 
 
        protected override void OnCreate (Bundle savedInstanceState) 
        { 
            base.OnCreate (savedInstanceState); 
 
            SetContentView (Resource.Layout.Main); 
 
            _adapter = new ListAdapter (this); 
 
            var listView = FindViewById<ListView> (Resource.Id.listView); 
            listView.Adapter = adapter; 
        } 
    } 

And voila! Try running the application and watching the ListView update with the images in your device's Gallery folder. Congratulations! You have just developed your first Xamarin.Android application. Now we must replicate this approach for the iOS version.

Note

Notice the challenge with context switching when jumping back and forth between Android and iOS; it can get confusing. Luckily, with Xamarin we keep to just one programming language, which helps reduce the complexity.

You have been reading a chapter from
Xamarin Blueprints
Published in: Sep 2016
Publisher: Packt
ISBN-13: 9781785887444
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image