Spanish Reducir el tamaño de una imagen y centrarla en pantalla

tomky

Active Member
Licensed User
Siguiendo y corrigiendo un poco el ejemplo de Carles Escudé aquí, y las lecciones de bgsoft para tratar con imágenes, compartimos este código para reducir el tamaño de una imagen y centrarla en pantalla.
Saludos.

B4X:
Sub Process_Globals
End Sub

Sub Globals

    Dim b, b2 As Bitmap
    Dim Xf As Long, Yf As Long
    Dim LeftImagen , TopImagen As Int
    Dim iv As ImageView
End Sub

Sub Activity_Create(FirstTime As Boolean)

    'Leemos la imagen, en este caso de la memoria interna
    b = LoadBitmap(File.DirRootExternal, "nombreImagenOriginal.jpg")


    ' CALCULAR RELACION ASPECTO IMAGEN
    Dim Xi As Long, Yi As Long, XdivY As Double

    Xi = b.Width
    Yi = b.Height
    XdivY = Xi / Yi
 
    If XdivY >= 1 Then
        Xf = b.Width * 0.5   'AnchoMaximoQueQueremos
        Yf = Xf / XdivY         'Para guardar la proporción
    Else
        Yf = b.Height * 0.3   'AltoMaximoQueQueremos
        Xf = Yf * XdivY
    End If


    b2 = changeImageSize(b, Xf, Yf)        'Reducción


    Dim out As OutputStream    'guardar en tamaño menor
    out = File.OpenOutput (File.DirRootExternal, "nombreImagenReducida.jpg", False)
    b2.WriteToStream(out, 100, "JPEG")
    out.Close


    ' Para centrar el imageView en pantalla
    LeftImagen = (100%x-Xf) / 2
    TopImagen = (100%y-Yf) / 2


    iv.Initialize("")
    iv.Gravity = Gravity.FILL
    Activity.AddView(iv, LeftImagen, TopImagen, Xf, Yf)
    iv.Bitmap = b2
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub changeImageSize(bmp As Bitmap, destWidth As Int, destHeight As Int) As Bitmap

    Private imv As ImageView
    Private cvs As Canvas
    Dim pnl As Panel

    pnl.Initialize("pnl")
    imv.Initialize("imv")
    pnl.AddView(imv, 0, 0, destWidth, destHeight)    'tamaño final del lienzo
    cvs.Initialize(imv)

    Dim rSrc As Rect
    Dim rDest As Rect

    rSrc.Initialize(0, 0, bmp.Width, bmp.Height)
    rDest.Initialize(0, 0, destWidth, destHeight)
    cvs.DrawBitmap(bmp, rSrc, rDest)

    imv.Invalidate

    Return imv.Bitmap
End Sub
 
Last edited:
Top