public AndroidGraphics.Bitmap Transform(AndroidGraphics.Bitmap p0) { AndroidGraphics.Bitmap result = null; try { var newWidth = p0.Width; var newHeight = (int)(p0.Height * 0.95); var x = (p0.Width - newWidth) / 2; var y = (p0.Height - newHeight) / 2; result = AndroidGraphics.Bitmap.CreateBitmap(p0, x, y, newWidth, newHeight); return(result); } catch { // If we hit any problems, just return the original return(p0); } finally { if (result != p0) { p0.Recycle(); } } }
public Bitmap Transform(Bitmap source) { int size = Math.Min(source.Width, source.Height); int width = (source.Width - size) / 2; int height = (source.Height - size) / 2; var bitmap = Bitmap.CreateBitmap(size, size, Bitmap.Config.Argb4444); var canvas = new Canvas(bitmap); var paint = new Paint(); var shader = new BitmapShader(source, BitmapShader.TileMode.Clamp, BitmapShader.TileMode.Clamp); if (width != 0 || height != 0) { // source isn't square, move viewport to center var matrix = new Matrix(); matrix.SetTranslate(-width, -height); shader.SetLocalMatrix(matrix); } paint.SetShader(shader); paint.AntiAlias = true; float r = size / 2f; canvas.DrawCircle(r, r, r, paint); source.Recycle(); return bitmap; }
protected override Bitmap Transform(IBitmapPool bitmapPool, Bitmap source, int outWidth, int outHeight) { int size = Math.Min(source.Width, source.Height); int width = (source.Width - size) / 2; int height = (source.Height - size) / 2; Bitmap squaredBitmap = Bitmap.CreateBitmap(source, width, height, size, size); if (squaredBitmap != source) { source.Recycle(); } Bitmap bitmap = Bitmap.CreateBitmap(size, size, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.Clamp, BitmapShader.TileMode.Clamp); paint.SetShader(shader); paint.AntiAlias = true; float r = size / 2f; canvas.DrawCircle(r, r, r, paint); squaredBitmap.Recycle(); return BitmapResource.Obtain(bitmap, bitmapPool).Get(); }
// Rotates the bitmap by the specified degree. // If a new bitmap is created, the original bitmap is recycled. internal static Bitmap rotateImage(Bitmap b, int degrees) { if (degrees != 0 && b != null) { Matrix m = new Matrix(); m.SetRotate(degrees, (float)b.Width / 2, (float)b.Height / 2); try { Bitmap b2 = Bitmap.CreateBitmap( b, 0, 0, b.Width, b.Height, m, true); if (b != b2) { b.Recycle(); b = b2; } } catch (Java.Lang.OutOfMemoryError) { // We have no memory to rotate. Return the original bitmap. } } return b; }
public static void Recycle(Bitmap bitmap) { if (bitmap != null && !bitmap.IsRecycled) { bitmap.Recycle(); System.GC.Collect(); } }
private static void DisposeBitmap(Bitmap bitmap) { if (bitmap != null) { if (!bitmap.IsRecycled) { bitmap.Recycle(); } bitmap.Dispose(); } }
public Bitmap Transform (Bitmap bitmap) { int size = Math.Min(bitmap.Width, bitmap.Height); int x = (bitmap.Width - size) / 2; int y = (bitmap.Height - size) / 2; Bitmap result = Bitmap.CreateBitmap(bitmap, x, y, size, size); if (result != bitmap) { bitmap.Recycle(); } return result; }
public Bitmap Transform(Bitmap source) { int size = Math.Min(source.Width / 3, source.Height); int x = (source.Width - size) / 3; int y = (source.Height - size) / 2; Bitmap result = Bitmap.CreateBitmap(source, x, y, size, size); if (result != source) { source.Recycle(); } return result; }
private async void SetMetaData(int position, string title, string artist, ThumbnailSet thumbnails) { string filePath = queue[position].Path; await Task.Run(async() => { Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite); var meta = TagLib.File.Create(new StreamFileAbstraction(filePath, stream, stream)); meta.Tag.Title = title; meta.Tag.Performers = new string[] { artist }; meta.Tag.Album = title + " - " + artist; meta.Tag.Comment = queue[position].YoutubeID; IPicture[] pictures = new IPicture[1]; Bitmap bitmap = Picasso.With(this).Load(await YoutubeManager.GetBestThumb(thumbnails)).Transform(new RemoveBlackBorder(true)).MemoryPolicy(MemoryPolicy.NoCache).Get(); byte[] data; using (var MemoryStream = new MemoryStream()) { bitmap.Compress(Bitmap.CompressFormat.Png, 0, MemoryStream); data = MemoryStream.ToArray(); } bitmap.Recycle(); pictures[0] = new Picture(data); meta.Tag.Pictures = pictures; meta.Save(); stream.Dispose(); }); MediaScannerConnection.ScanFile(this, new string[] { filePath }, null, this); if (queue[position].PlaylistName == null) { queue[position].State = DownloadState.Completed; } else { queue[position].State = DownloadState.Playlist; } if (!queue.Exists(x => x.State == DownloadState.None || x.State == DownloadState.Downloading || x.State == DownloadState.Initialization || x.State == DownloadState.MetaData || x.State == DownloadState.Playlist)) { StopForeground(true); DownloadQueue.instance?.Finish(); queue.Clear(); } else { UpdateList(position); } }
protected override Bitmap Transform(Bitmap source) { int width = source.Width; int height = source.Height; Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); paint.AntiAlias = true; paint.SetShader(new BitmapShader(source, Shader.TileMode.Clamp, Shader.TileMode.Clamp)); canvas.DrawRoundRect(new RectF(margin, margin, width - margin, height - margin), radius, radius, paint); source.Recycle(); return bitmap; }
private void FreeBitmap() { if (bitmap == null) { return; } // free and recycle the bitmap data if (bitmap.Handle != IntPtr.Zero && !bitmap.IsRecycled) { bitmap.Recycle(); } bitmap.Dispose(); bitmap = null; }
void LoadTexture(Context context, int resourceId, int tex_id) { GL.BindTexture(TextureTarget.Texture2D, tex_id); // setup texture parameters GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.NearestMipmapLinear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat); Android.Graphics.Bitmap b = BitmapFactory.DecodeResource(context.Resources, resourceId); Android.Opengl.GLUtils.TexImage2D((int)All.Texture2D, 0, b, 0); b.Recycle(); GL.GenerateMipmap(TextureTarget.Texture2D); }
protected override Bitmap Transform(Bitmap source) { int width = source.Width; int height = source.Height; Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); paint.AntiAlias = true; paint.SetColorFilter(new PorterDuffColorFilter(mColor, PorterDuff.Mode.SrcAtop)); canvas.DrawBitmap(source, 0, 0, paint); source.Recycle(); return bitmap; }
protected override Bitmap Transform(Bitmap source) { int width = source.Width; int height = source.Height; Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(bitmap); ColorMatrix saturation = new ColorMatrix(); saturation.SetSaturation(0f); Paint paint = new Paint(); paint.SetColorFilter(new ColorMatrixColorFilter(saturation)); canvas.DrawBitmap(source, 0, 0, paint); source.Recycle(); return bitmap; }
protected override Android.Graphics.Bitmap Transform(Android.Graphics.Bitmap source) { Bitmap outBitmap = Bitmap.CreateBitmap(source.Width, source.Height, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(outBitmap); canvas.DrawBitmap(source, 0, 0, null); RenderScript rs = RenderScript.Create(mContext); Allocation overlayAlloc = Allocation.CreateFromBitmap(rs, outBitmap); ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.Create(rs, overlayAlloc.Element); blur.SetInput(overlayAlloc); blur.SetRadius(mRadius); blur.ForEach(overlayAlloc); overlayAlloc.CopyTo(outBitmap); source.Recycle(); rs.Destroy(); return(outBitmap); }
public Bitmap Transform(Bitmap source) { Bitmap result = Bitmap.CreateBitmap(source.Width, source.Height, source.GetConfig()); Bitmap noise; try { noise = picasso.Load(Resource.Drawable.noise).Get(); } catch (Exception) { throw new Exception("Failed to apply transformation! Missing resource."); } BitmapShader shader = new BitmapShader(noise, Shader.TileMode.Repeat, Shader.TileMode.Repeat); ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.SetSaturation(0); ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix); Paint paint = new Paint(PaintFlags.AntiAlias); paint.SetColorFilter(filter); Canvas canvas = new Canvas(result); canvas.DrawBitmap(source, 0, 0, paint); paint.SetColorFilter(null); paint.SetShader(shader); paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.Multiply)); canvas.DrawRect(0, 0, canvas.Width, canvas.Height, paint); source.Recycle(); noise.Recycle(); return result; }
/// <summary> /// Saves the cropped image /// </summary> /// <param name="croppedImage">the cropped image</param> /// <param name="saveUri"> the uri to save the cropped image to</param> internal void SaveOutput(Bitmap croppedImage, Android.Net.Uri saveUri) { if (saveUri == null) { Log.Error(this.GetType().Name, "invalid image url"); return; } using (var outputStream = context.ContentResolver.OpenOutputStream(saveUri)) { if (outputStream != null) { croppedImage.Compress(outputFormat, 75, outputStream); } } croppedImage.Recycle(); }
Bitmap changeOrientation (string filePath, Bitmap bitmap, int orientation) { var matrix = new Matrix (); switch (orientation) { case 2: matrix.SetScale (-1, 1); break; case 3: matrix.SetRotate (180); break; case 4: matrix.SetRotate (180); matrix.PostScale (-1, 1); break; case 5: matrix.SetRotate (90); matrix.PostScale (-1, 1); break; case 6: matrix.SetRotate (90); break; case 7: matrix.SetRotate (-90); matrix.PostScale (-1, 1); break; case 8: matrix.SetRotate (-90); break; default: return bitmap; } try { Bitmap oriented = Bitmap.CreateBitmap (bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true); bitmap.Recycle (); return oriented; } catch (Exception e) { return bitmap; } }
private void DismissBitmap(Bitmap bitmap) { if (bitmap != null) { bitmap.Recycle(); bitmap.Dispose(); GC.Collect(); } }
public void InitWithBitmap(Bitmap imageSource, ALL11 filter) { //TODO: Android.Opengl.GLUtils.GetInternalFormat() _format = SurfaceFormat.Color; if (imageSource.HasAlpha) _format = SurfaceFormat.Color; if (GraphicsDevice.OpenGLESVersion == OpenTK.Graphics.GLContextVersion.Gles2_0) { _width = imageSource.Width; _height = imageSource.Height; } else { // scale up bitmap to be power of 2 dimensions but dont exceed 1024x1024. // Note: may not have to do this with OpenGL 2+ _width = (int)Math.Pow(2, Math.Min(10, Math.Ceiling(Math.Log10(imageSource.Width) / Math.Log10(2)))); _height = (int)Math.Pow(2, Math.Min(10, Math.Ceiling(Math.Log10(imageSource.Height) / Math.Log10(2)))); } _size.Width = _width; _size.Height = _height; using (Bitmap imagePadded = Bitmap.CreateBitmap(_width, _height, Bitmap.Config.Argb8888)) { Canvas can = new Canvas(imagePadded); can.DrawARGB(0, 0, 0, 0); can.DrawBitmap(imageSource, 0, 0, null); if (GraphicsDevice.OpenGLESVersion == OpenTK.Graphics.GLContextVersion.Gles2_0) { GL11.GenTextures(1, ref _name); GL11.BindTexture(ALL11.Texture2D, _name); GL11.TexParameter(ALL11.Texture2D, ALL11.TextureMinFilter, (int)filter); GL11.TexParameter(ALL11.Texture2D, ALL11.TextureMagFilter, (int)filter); Android.Opengl.GLUtils.TexImage2D((int)ALL11.Texture2D, 0, imagePadded, 0); // free bitmap imageSource.Recycle(); // error checking int errAndroidGL = Android.Opengl.GLES20.GlGetError(); ALL20 errGenericGL = GL20.GetError(); if (errAndroidGL != Android.Opengl.GLES20.GlNoError || errGenericGL != ALL20.NoError) Console.WriteLine(string.Format("OpenGL ES 2.0:\n\tAndroid error: {0,10:X}\n\tGeneric error: {1, 10:X}", errAndroidGL, errGenericGL)); } else { GL20.GenTextures(1, ref _name); GL20.BindTexture(ALL20.Texture2D, _name); GL20.TexParameter(ALL20.Texture2D, ALL20.TextureMinFilter, (int)filter); GL20.TexParameter(ALL20.Texture2D, ALL20.TextureMagFilter, (int)filter); Android.Opengl.GLUtils.TexImage2D((int)ALL20.Texture2D, 0, imagePadded, 0); } } _maxS = _size.Width / (float)_width; _maxT = _size.Height / (float)_height; }
protected override void OnDraw(Android.Graphics.Canvas canvas) { if (mixerValue == null) // don't do anything if we're not connected to a mixervalue return; if (bmp == null) { bmp = BitmapFactory.DecodeResource (Resources, Resource.Drawable.Fader_Knob); Bitmap scaled = Bitmap.CreateScaledBitmap (bmp, 25, 55, true); bmp.Recycle(); bmp = scaled; } int margin = 60; float radius = 4; int center = (Width / 2) + 5; int minY1 = margin - (bmp.Height / 2); int maxY1 = Height - margin - (bmp.Height / 2); rangeY = maxY1 - minY1; float factor = (float)mixerValue.GetValue() / (float)maxValue; bitmapX1 = center - bmp.Width / 2; bitmapY1 = maxY1 - (int)(factor * (float)rangeY); base.OnDraw (canvas); var paint = new Paint (); paint.Color = Color.White; paint.TextAlign = Paint.Align.Center; paint.TextSize = (float)12.0; paint.SetTypeface(Typeface.DefaultBold); if (channel_name != null) canvas.DrawText (channel_name, center - 5, 14, paint); // align with pan control int levelX1 = center - (bmp.Width / 2) - 2; int levelX2 = center + (bmp.Width / 2); paint.TextSize = (float)10.0; paint.TextAlign = Paint.Align.Right; foreach (var level in faderLevels) { float factorLevel = (float)level.Key / (float)maxValue; int levelY = maxY1 - (int)(factorLevel * (float)rangeY) + (bmp.Height / 2); canvas.DrawRect (levelX1, levelY - 1, levelX2, levelY, paint); canvas.DrawText (level.Value, levelX1 - 4, levelY + 3, paint); } paint.Color = Color.DarkGray; RectF rect = new RectF (center - 2, margin, center + 2, Height - margin); canvas.DrawRoundRect(rect, radius, radius, paint); paint.Color = Color.Black; rect = new RectF (center - 1, margin + 1, center + 1, Height - margin - 1); canvas.DrawRoundRect(rect, radius, radius, paint); bitmapX2 = bitmapX1 + bmp.Width; bitmapY2 = bitmapY1 + bmp.Height; if (isActive) { paint.Alpha = 255; } else { paint.Alpha = 180; } canvas.DrawBitmap (bmp, bitmapX1, bitmapY1, paint); //bmp.Recycle (); }
private static TexInfo CreateTexInfoFromBitmap(Bitmap bitmap) { TexInfo ret = null; if (bitmap != null) { ret = new TexInfo (); ret.has_alpha = bitmap.HasAlpha; ret.needs_alpha_test = false; // ad-hock GLES20.GlPixelStorei(GLES20.GlUnpackAlignment, 1); int[] tex = new int[1]; GLES20.GlGenTextures(1, tex, 0); ret.tex = tex [0]; GLES20.GlBindTexture(GLES20.GlTexture2d, ret.tex); GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge); GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge); GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlLinear); GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlLinear); GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0); bitmap.Recycle (); } return ret; }
private void saveOutput(Bitmap croppedImage) { if (saveUri != null) { try { using (var outputStream = ContentResolver.OpenOutputStream(saveUri)) { if (outputStream != null) { croppedImage.Compress(outputFormat, 75, outputStream); } } } catch (Exception ex) { Log.Error(this.GetType().Name, ex.Message); } Bundle extras = new Bundle(); SetResult(Result.Ok, new Intent(saveUri.ToString()) .PutExtras(extras)); } else { Log.Error(this.GetType().Name, "not defined image url"); } croppedImage.Recycle(); Finish(); }
//--->TERMINAN COSAS DE SELECCIONAR IMAGEN DE LA CAMARA<---// //INICIA PROCESAR IMAGENES public void ProcesarImagenes (GridLayout imgcomprev, int limite, TextView imgrestantes){ if(imgcount<limite){ GetImage(((b, p) => { int countimage = p.Count; Log.Debug("GetImage","Imagenes en el list: "+countimage); int imgcount2=imgcount+countimage; Log.Debug("GetImage","Imagenes totales: "+imgcount2); if(imgcount2>limite){ //int total = limite-imgcount; var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition); Snackbar .Make (fabee, "No puedes publicar mas de "+limite+" imágenes!", Snackbar.LengthLong) .SetAction ("Ok", (view) => { }) .Show (); }else{ //ya aqui se hace lo de poner cada imagen imgcount=imgcount2; Log.Debug("GetImage","Nuevo imgcount: "+imgcount); for(int i=0; i<countimage; i++){ //filenameres= p[i].Substring (p[i].LastIndexOf ("/") + 1); //fileextres= filenameres.Substring (filenameres.LastIndexOf(".")+1); //Si por algún acaso la memoria no ha sido liberada, la liberamos primero. if (imagencomentario != null && !imagencomentario.IsRecycled) { imagencomentario.Recycle(); imagencomentario = null; } Java.IO.File f = new Java.IO.File(p[i]); stream = this.ContentResolver.OpenInputStream(Android.Net.Uri.FromFile(f)); imagencomentario=BitmapFactory.DecodeStream(stream); //POR AHORA VAMOS A QUITAR ESTO PARA QUE LO HAGA MAS RAPIDO Y DEJAMOS QUE EL SERVIDOR SE ENCARGUE /* try{ Android.Media.ExifInterface ei = new Android.Media.ExifInterface(p[i]); var orientation= ei.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, -1); Log.Debug("GetImageCamera","El orientation es: "+orientation); if(orientation==1){ //No hagas nada, si está bien la imagen. No tiene caso .-. }else{ Log.Debug("Orientation", "Inicia Mutable"); Bitmap mutable; Canvas cnv; Matrix matrix; Log.Debug("Orientation", "Termina Mutable"); Log.Debug("Orientation", "Inicia Switch"); switch(orientation){ case 6: //90 grados mutable = imagencomentario.Copy(Bitmap.Config.Argb8888, true); cnv = new Canvas(mutable); matrix = new Matrix(); Log.Debug("Orientation", "90 Grados"); matrix.PostRotate(90); imagencomentario=Bitmap.CreateBitmap(mutable, 0, 0, imagencomentario.Width, imagencomentario.Height, matrix, true); break; case 3: //180 grados mutable = imagencomentario.Copy(Bitmap.Config.Argb8888, true); cnv = new Canvas(mutable); matrix = new Matrix(); Log.Debug("Orientation", "180 Grados"); matrix.PostRotate(180); imagencomentario=Bitmap.CreateBitmap(mutable, 0, 0, imagencomentario.Width, imagencomentario.Height, matrix, true); break; case 8: //270 grados mutable = imagencomentario.Copy(Bitmap.Config.Argb8888, true); cnv = new Canvas(mutable); matrix = new Matrix(); Log.Debug("Orientation", "270 Grados"); matrix.PostRotate(270); imagencomentario=Bitmap.CreateBitmap(mutable, 0, 0, imagencomentario.Width, imagencomentario.Height, matrix, true); break; default: Log.Debug("Orientation", "0 Grados (0 360, como se quiera ver :P)"); //0 grados //No hagas nada break; }; Log.Debug("Orientation", "Termina Switch"); }//ELSE orientation = 1 }catch(Exception ex){ Log.Debug("Orientation", "ERROR! Posiblemente no hay EXIF: "+ex); } */ if(imagencomentario!=null){ //Toast.MakeText(this, "Si se creó el Bitmap!!!", ToastLength.Long).Show(); //Lo añadimos a la lista //Bitmap tmp = imagencomentario; Log.Debug("FOSSBYTES","Inicia conversión a bytes!"); byte[] tmp2 = PathToByte2(p[i]); Log.Debug("FOSSBYTES","Termina conversión a bytes!"); fossbytes.Add(tmp2); //Toast.MakeText(this, "Elementos en lista: "+contenedorimagenes.Count, ToastLength.Long).Show(); //aqui haremos el img //Creamos el imageview con sus parámetros ImageView prev = new ImageView(this); imgcomprev.AddView(prev); GridLayout.LayoutParams lp = new GridLayout.LayoutParams(); lp.SetMargins(15,15,0,15); lp.Width=130; lp.Height=130; prev.LayoutParameters=lp; prev.SetScaleType(ImageView.ScaleType.CenterCrop); prev.SetImageBitmap(Bitmap.CreateScaledBitmap(imagencomentario, 175, 175, false)); //prev.StartAnimation(bounce); //imgcount++; //Liberamos la memoria Inmediatamente! if (imagencomentario != null && !imagencomentario.IsRecycled) { imagencomentario.Recycle(); imagencomentario = null; } //Mala idea, esto causó que tronara .-. si lo voy a hacer pero cuando no tenga que usarlo }else{//por si algun acaso intenta procesar una ruta null var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition); Snackbar .Make (fabee, "Ocurrió un error. Por favor intenta con una imágen diferente", Snackbar.LengthLong) .SetAction ("Ok", (view) => { }) .Show (); break; } }//TERMINA EL FOR PARA CADA IMAGEN int restantes=limite-imgcount; if(restantes==0){ imgrestantes.Text="¡Excelente!"; }else{ imgrestantes.Text="Puedes cargar "+restantes+" imágenes más!"; } }//TERMINA EL ELSE DE COMPROBAR SI HAY MAS IMAGENES DE LAS QUE SE PUEDEN CARGAR }));//GETIMAGE }else{ var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition); Snackbar .Make (fabee, "Solo puedes subir hasta 3 imágenes!", Snackbar.LengthLong) .SetAction ("Ok", (view) => { }) .Show (); }//ELSE COUNTIMAGES < 3 }
public void InitWithBitmapGL20(Bitmap imageSource, GL20.All filter) { //TODO: Android.Opengl.GLUtils.GetInternalFormat() //Android.Opengl.GLUtils.GetInternalFormat(imageSource); openGLVersion = GLContextVersion.Gles2_0; _format = SurfaceFormat.Color; if (imageSource.HasAlpha) _format = SurfaceFormat.Color; _width = imageSource.Width; _height = imageSource.Height; _size.Width = imageSource.Width; _size.Height = imageSource.Height; GL20.GL.GenTextures(1, ref _name); GL20.GL.BindTexture(GL20.All.Texture2D, _name); GL20.GL.TexParameter( GL20.All.Texture2D, GL20.All.TextureMinFilter, (int)filter); GL20.GL.TexParameter( GL20.All.Texture2D, GL20.All.TextureMagFilter, (int)filter); GL20.GL.TexParameter( GL20.All.Texture2D, GL20.All.TextureWrapS, (int)GL20.All.ClampToEdge); GL20.GL.TexParameter( GL20.All.Texture2D, GL20.All.TextureWrapT, (int)GL20.All.ClampToEdge); Android.Opengl.GLUtils.TexImage2D((int)GL20.All.Texture2D, 0, imageSource, 0); imageSource.Recycle(); //int errAndroidGL = Android.Opengl.GLES20.GlGetError(); //GL20.All errGenericGL = GL20.GL.GetError(); //if(errAndroidGL != Android.Opengl.GLES20.GlNoError || errGenericGL != GL20.All.NoError ) // Console.WriteLine(string.Format("OpenGL-ES 2.0:\n\tAndroid:{0,10:X}\n\tGeneric:{0, 10:X}", errAndroidGL, errGenericGL)); _maxS = _size.Width / (float)_width; _maxT = _size.Height / (float)_height; }
/// <summary> /// Rotates the image to the correct orientation /// </summary> /// <param name="bitmap"></param> /// <param name="orientation"></param> /// <returns></returns> public static Bitmap RotateBitmap( Bitmap bitmap, int orientation ) { Matrix matrix = new Matrix(); switch( orientation ) { case 1: return bitmap; case 2: matrix.SetScale( -1, 1 ); break; case 3: matrix.SetRotate( 180 ); break; case 4: matrix.SetRotate( 180 ); matrix.PostScale( -1, 1 ); break; case 5: matrix.SetRotate( 90 ); matrix.PostScale( -1, 1 ); break; case 6: matrix.SetRotate( 90 ); break; case 7: matrix.SetRotate( -90 ); matrix.PostScale( -1, 1 ); break; case 8: matrix.SetRotate( -90 ); break; default: return bitmap; } Bitmap bmRotated = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true); bitmap.Recycle(); return bmRotated; }
// This gets called when the drawing surface is ready protected override void OnLoad (EventArgs e) { base.OnLoad (e); try { // Clear the current Context GraphicsContext.MakeCurrent (null); // Create a secondary context using the same information the primary // context was created with backgroundContext = new AndroidGraphicsContext(GraphicsMode, WindowInfo, GraphicsContext, ContextRenderingApi, GraphicsContextFlags.Embedded); }catch { // secondary context not supported backgroundContext = null; } MakeCurrent(); var vertexShader = LoadShader(ShaderType.VertexShader, vertexShaderCode); var fragmentShader = LoadShader(ShaderType.FragmentShader, fragmentShaderCode); program = GL.CreateProgram (); // create empty OpenGL Program GL.AttachShader (program, vertexShader); // add the vertex shader to program GL.AttachShader (program, fragmentShader); // add the fragment shader to program GL.BindAttribLocation (program, ATTRIB_VERTEX, "position"); GL.BindAttribLocation (program, ATTRIB_TEXCOORD, "texcoord"); GL.LinkProgram (program); // create OpenGL program executables uniformTextureLocation = GL.GetUniformLocation (program, "texture"); if (vertexShader != 0) { GL.DetachShader (program, vertexShader); GL.DeleteShader (vertexShader); } if (fragmentShader != 0) { GL.DetachShader (program, fragmentShader); GL.DeleteShader (fragmentShader); } GL.Viewport (0, 0, Width, Height); // Run the render loop Run (); Task.Factory.StartNew (() => { //Thread.Sleep(500); // load the bitmap bitmap = BitmapFactory.DecodeResource (Context.Resources, Resource.Drawable.f_spot); // the device may or may not support a background Context. But rather than // duplicating this code we just create an Action which we can invoke on this // background thread later or queue to be executed on the rendering thread. Action acton = new Action (() => { GL.Enable (EnableCap.Texture2D); GL.GenTextures(1, out textureid); GL.ActiveTexture (TextureUnit.Texture0); GL.BindTexture (TextureTarget.Texture2D, textureid); // setup texture parameters GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); Android.Opengl.GLUtils.TexImage2D ((int)TextureTarget.Texture2D, 0, bitmap, 0); // make sure the texture is pushed to the GPU. GL.Flush(); // make sure we free resources bitmap.Recycle(); bitmap.Dispose(); bitmap = null; }); // take a lock so the main rendering thread does not try to draw anything // there are other ways to do this, but its is probably the simplest lock (lockobject) { if (backgroundContext != null) { // Clear the current context bound to the Display backgroundContext.MakeCurrent (null); // make this context active backgroundContext.MakeCurrent (WindowInfo); // do our processing acton.Invoke (); // clear the current context again so we don't error on the main thread backgroundContext.MakeCurrent (null); } else { // Secondary Context's are not supported on this device // queue the action for execution later. actions.Enqueue (acton); } } }); }