BitmapFactory.DecodeByteArrayAsync
private async void OnAsyncDownImage(object sender, EventArgs e) { this._webclient = new WebClient(); var url = new Uri("http://pic1.sc.chinaz.com/files/pic/pic9/201404/apic105.jpg"); byte[] bytes = null; try { bytes = await this._webclient.DownloadDataTaskAsync(url); this._webclient.DownloadProgressChanged += this.OnProgressChanged; } catch (TaskCanceledException) { // Console.WriteLine("i cancel the async download ~~~~~~~~~~~~~~~~~"); Log.Warn("async canceled", "i can cancel the async methord"); return; } catch (Exception error) { // throw; Console.Out.WriteLine("this is error message :" + error.Message); return; } var options = new BitmapFactory.Options { InJustDecodeBounds = true, }; if (bytes.Length != 0) { Console.Out.WriteLine("length not 0"); await BitmapFactory.DecodeByteArrayAsync(bytes, 0, bytes.Length, options); Console.Out.WriteLine( "output width :{0}; output height :{1}; imageview width :{2}; imageheight :{3}", options.OutWidth, options.OutHeight, this._imagevew.Width, this._imagevew.Height); //simplesize calculate /* options.InSampleSize = options.OutWidth > options.OutHeight ? options.OutHeight / _imagevew.Height : options.OutWidth / _imagevew.Width;*/ options.InSampleSize = calculateInSampleSize(options, this._imagevew.Width, this._imagevew.Height); options.InJustDecodeBounds = false; Bitmap image = await BitmapFactory.DecodeByteArrayAsync(bytes, 0, bytes.Length, options); Console.Out.WriteLine("image the width is :{0}; image the height is :{1}", image.Width, image.Height); this._imagevew.SetImageBitmap(image); } else { Console.Out.WriteLine("length is 0"); } Console.Out.WriteLine("i end the download image"); }
如果不使用 calculateInSampleSize ,那么imageview的图像就会一会打一会小
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image int height = options.OutHeight; int width = options.OutWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { int halfHeight = height / 2; int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; }

浙公网安备 33010602011771号