Android Question How to set background image in responsive and center of the panel with corner redius and border

megzz

Member
Licensed User
Longtime User
hi
i need to set image In the form of FILL and not unform to background of panel with border and redius of panel
for example :
shekaf.jpg

-place A Should not be shown
-only show place B
-my image is Square
(centering picture and fill this)


i can set image to panel In the form FILL and not unform without border and corner redius , plz help me!
B4X:
Dim img As ImageView
    img.Initialize("")
    img.Bitmap = LoadBitmap(File.DirAssets,"hhh.jpg")
    img.Gravity = Gravity.FILL
    Dim panel As Panel
    panel.Initialize("")
    Dim x As Int = 100%x-10dip
    panel.AddView(img,0,(250dip/2)-(x/2)  ,x,x-5dip)
    ScrollView1.Panel.AddView(panel,5dip,5dip,100%x-10dip,250dip)
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
SS-2017-11-15_12.21.51.png


Based on XUI library:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim base As B4XView = xui.CreatePanel("")
   Dim bmp As B4XBitmap = xui.LoadBitmapResize(File.DirAssets, "shekaf.jpg", 100%x, 100%y, True)
   Activity.AddView(base, 10dip, 30%y, 100%x - 20dip, 40%y) 'this line defines the visible area
   Dim borderWidth As Int = 6dip
   base.SetColorAndBorder(xui.Color_Transparent, borderWidth, xui.Color_Red, 0)
   Dim imgView As B4XView = xui.CreatePanel("")
   base.AddView(imgView, borderWidth, borderWidth, base.Width - 2 * borderWidth, base.Height - 2 * borderWidth)
   Dim ImageOffsetX = 50%x - bmp.Width / 2, ImageOffsetY = 50%y - bmp.Height / 2 As Int
   imgView.SetBitmap(bmp.Crop(base.Left - ImageOffsetX, base.Top - ImageOffsetY, base.Width, base.Height))
End Sub

Making the corners round is more complicated as the panel's round corners do not clip the child views.
 
Upvote 0

megzz

Member
Licensed User
Longtime User
Based on XUI library:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim base As B4XView = xui.CreatePanel("")
   Dim bmp As B4XBitmap = xui.LoadBitmapResize(File.DirAssets, "shekaf.jpg", 100%x, 100%y, True)
   Activity.AddView(base, 10dip, 30%y, 100%x - 20dip, 40%y) 'this line defines the visible area
   Dim borderWidth As Int = 6dip
   base.SetColorAndBorder(xui.Color_Transparent, borderWidth, xui.Color_Red, 0)
   Dim imgView As B4XView = xui.CreatePanel("")
   base.AddView(imgView, borderWidth, borderWidth, base.Width - 2 * borderWidth, base.Height - 2 * borderWidth)
   Dim ImageOffsetX = 50%x - bmp.Width / 2, ImageOffsetY = 50%y - bmp.Height / 2 As Int
   imgView.SetBitmap(bmp.Crop(base.Left - ImageOffsetX, base.Top - ImageOffsetY, base.Width, base.Height))
End Sub

Making the corners round is more complicated as the panel's round corners do not clip the child views.



Give me an example to you in any way you can ( with border and corner radius)

Tnx .
 
Upvote 0

megzz

Member
Licensed User
Longtime User
SS-2017-11-15_12.21.51.png


Based on XUI library:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim base As B4XView = xui.CreatePanel("")
   Dim bmp As B4XBitmap = xui.LoadBitmapResize(File.DirAssets, "shekaf.jpg", 100%x, 100%y, True)
   Activity.AddView(base, 10dip, 30%y, 100%x - 20dip, 40%y) 'this line defines the visible area
   Dim borderWidth As Int = 6dip
   base.SetColorAndBorder(xui.Color_Transparent, borderWidth, xui.Color_Red, 0)
   Dim imgView As B4XView = xui.CreatePanel("")
   base.AddView(imgView, borderWidth, borderWidth, base.Width - 2 * borderWidth, base.Height - 2 * borderWidth)
   Dim ImageOffsetX = 50%x - bmp.Width / 2, ImageOffsetY = 50%y - bmp.Height / 2 As Int
   imgView.SetBitmap(bmp.Crop(base.Left - ImageOffsetX, base.Top - ImageOffsetY, base.Width, base.Height))
End Sub

Making the corners round is more complicated as the panel's round corners do not clip the child views.


i can create this perfect !!


B4X:
    Dim img As ImageView
    img.Initialize("")
    explorepost_waveformbg.Panel.AddView(img,5dip,5dip,100%x-10dip,220dip)
    FitCenterBitmap(img,File.DirAssets,"xcover.jpg",2)

    Dim cnv As Canvas
    cnv.Initialize(img)
    Dim Out As OutputStream
    Out = File.OpenOutput(File.DirRootExternal, "PnlImg.png", False)
    cnv.Bitmap.WriteToStream(Out, 100, "PNG")
    Out.Close
   
    img.RemoveView
   
    Dim img As ImageView
    img.Initialize("")
    'img.Gravity = Bit.Or(Gravity.FILL,Gravity.CENTER)
    Dim tempbitmap As Bitmap
    explorepost_waveformbg.Panel.AddView(img,5dip,5dip,100%x-10dip,220dip)
    tempbitmap.Initialize(File.DirRootExternal, "PnlImg.png")
    img.Bitmap = nativeMe.RunMethod("toRoundCornerexplor",Array(tempbitmap, Colors.rgb(179, 179, 179)))




#If Java

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.provider.MediaStore.Images;
import android.text.TextUtils;
import android.view.Gravity;
import android.content.res.Resources;
import android.util.TypedValue;
import android.util.DisplayMetrics;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;




    public Bitmap rotateImage(Bitmap bitmap, int rotate) {
        if (bitmap == null) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.setRotate(rotate);
        Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        if (rotated != null && !rotated.equals(bitmap)) {
//            bitmap.recycle();
            bitmap = rotated;
        }
        return bitmap;
    }

    public Bitmap squareImage(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        if (width == height) {
            BA.Log("no need to square image");
            return bitmap;
        }
        int x = (height < width) ? ((width - height) / 2) : 0;
        int y = (width < height) ? ((height - width) / 2) : 0;
        int pixels = width < height ? width : height;
        Bitmap square = Bitmap.createBitmap(bitmap, x, y, pixels, pixels);
        return square;
    }
   

    public Bitmap toRounded(Bitmap bitmap,
            int color, int borderDips, int desireWidth) {
        try {
            Bitmap bitmap0 = squareImage(bitmap);
            Bitmap bitmap1 = resizeImage(bitmap0, desireWidth, desireWidth,
                    true);
            int toPX = dp2px(borderDips);
            int maxBorder = (desireWidth / 2) / 5;
            maxBorder = maxBorder > 15 ? 15 : maxBorder;
            final int borderSizePx = toPX > maxBorder ? maxBorder : toPX;

            final int size = desireWidth;
            int center = (int) (size / 2);
            int left = (int) ((desireWidth - size) / 2);
            int top = (int) ((desireWidth - size) / 2);
            int right = left + size;
            int bottom = top + size;

            Bitmap output = Bitmap.createBitmap(size, size, Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final Paint paint = new Paint();

            final Rect src = new Rect(left, top, right, bottom);
            final Rect dst = new Rect(0, 0, size, size);

            canvas.drawARGB(0, 0, 0, 0);
            // draw border
            paint.setColor(color);
            paint.setAntiAlias(true);
            int radius = center - borderSizePx;
            canvas.drawCircle(center, center, radius, paint);
            // draw bitmap
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap1, src, dst, paint);
            paint.setXfermode(null);

            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth((float) borderSizePx);
            radius = center - borderSizePx / 2;
            canvas.drawCircle(center, center, radius, paint);
            canvas.save();
            return output;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    public Bitmap resizeImage(Bitmap bitmap, int desireWidth,
            int desireHeight, boolean isEnlarge) {
        if (bitmap == null || desireHeight <= 0 || desireWidth <= 0) {
            return null;
        }

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        if (width <= 0 || height <= 0) {
            return bitmap;
        }
        if (!isEnlarge && (width < desireWidth && height < desireHeight)) {
            return bitmap;
        }
        float scale;
        if (width < height) {
            scale = (float) desireHeight / (float) height;
            if (desireWidth < width * scale) {
                scale = (float) desireWidth / (float) width;
            }
        } else {
            scale = (float) desireWidth / (float) width;
        }

        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);

        return bitmap;
    }

    public int dp2px(int dip) {
        Resources resources = getResources();
        int px = Math
                .round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                        dip, resources.getDisplayMetrics()));
        return px;
    }

    public int px2dp(int px) {
        DisplayMetrics displayMetrics = getResources()
                .getDisplayMetrics();
        int dp = Math.round(px
                / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return dp;
    }

    public int sp2px(float sp) {
        final float scale = getResources().getDisplayMetrics().scaledDensity;
        int px = Math.round(sp * scale);
        return px;
    }


    public Bitmap toRoundCornerexplor(Bitmap bitmap, int color) {
        try {
            int w = bitmap.getWidth();
            int h = bitmap.getHeight();
            final int delta = dp2px(1);
            final float roundPx = dp2px(5);
            final Paint paint = new Paint();
            paint.setAntiAlias(true);

            /* draw round foreground */
            int foreW = w - 2 * delta;
            int foreH = h - 2 * delta;
            Bitmap foreBmp = Bitmap
                    .createBitmap(foreW, foreH, Config.ARGB_8888);
            Rect rect = new Rect(0, 0, foreW, foreH);
            RectF rectF = new RectF(rect);
            Canvas canvas0 = new Canvas(foreBmp);
            canvas0.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas0.drawBitmap(bitmap, null, rect, paint);

            /* draw round background */
            Drawable drawable = getDrawbale(color, (int) (delta + roundPx));
            drawable.setBounds(0, 0, w, h);
            Bitmap result = Bitmap.createBitmap(w, h, Config.ARGB_8888);
            Canvas canvas = new Canvas(result);
            drawable.draw(canvas);
            canvas.drawBitmap(foreBmp, delta, delta, null);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return bitmap;
        }
    }

    public GradientDrawable getDrawbale(int argb, int radius) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setCornerRadius(radius);
        drawable.setColor(argb);
        return drawable;
    }


    public Bitmap drawRing1(Bitmap bitmap, int deltaRadius,
            int color) {
        bitmap = squareImage(bitmap);   
        int w = bitmap.getWidth();
        int dia = deltaRadius * 2 + w;
        float radius = (float) dia / 2;
        Bitmap resultBitmap = Bitmap.createBitmap(dia, dia, Config.ARGB_8888);
        Paint paint = new Paint();
        paint.setColor(color);
        paint.setAlpha(128);
        paint.setAntiAlias(true);
        Canvas canvas = new Canvas(resultBitmap);
        canvas.drawCircle(radius, radius, radius, paint);
        canvas.drawBitmap(bitmap, deltaRadius, deltaRadius, null);
        return resultBitmap;
    }

   
   
    public static Bitmap drawLayoutDropShadow(Bitmap bitmap) {
        BlurMaskFilter blurFilter = new BlurMaskFilter(2,
                BlurMaskFilter.Blur.OUTER);
        Paint shadowPaint = new Paint();
        shadowPaint.setMaskFilter(blurFilter);
        int[] offsetXY = { 5, 5 };
        Bitmap shadowBitmap = bitmap.extractAlpha(shadowPaint, offsetXY);
        Bitmap shadowImage32 = shadowBitmap.copy(Bitmap.Config.ARGB_8888, true);
        Canvas c = new Canvas(shadowImage32);
        c.drawBitmap(bitmap, 0, 0, null);
        return shadowImage32;
    }
   
    public Bitmap blur(Bitmap bmp) {
        int iterations = 1;
        int radius = 8;
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int[] inPixels = new int[width * height];
        int[] outPixels = new int[width * height];
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bmp.getPixels(inPixels, 0, width, 0, 0, width, height);
        for (int i = 0; i < iterations; i++) {
            blur(inPixels, outPixels, width, height, radius);
            blur(outPixels, inPixels, height, width, radius);
        }
        bitmap.setPixels(inPixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
   
    public void blur(int[] in, int[] out, int width, int height,
            int radius) {
        int widthMinus1 = width - 1;
        int tableSize = 2 * radius + 1;
        int divide[] = new int[256 * tableSize];

        for (int index = 0; index < 256 * tableSize; index++) {
            divide[index] = index / tableSize;
        }

        int inIndex = 0;

        for (int y = 0; y < height; y++) {
            int outIndex = y;
            int ta = 0, tr = 0, tg = 0, tb = 0;

            for (int i = -radius; i <= radius; i++) {
                int rgb = in[inIndex + clamp(i, 0, width - 1)];
                ta += (rgb >> 24) & 0xff;
                tr += (rgb >> 16) & 0xff;
                tg += (rgb >> 8) & 0xff;
                tb += rgb & 0xff;
            }

            for (int x = 0; x < width; x++) {
                out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16)
                        | (divide[tg] << 8) | divide[tb];

                int i1 = x + radius + 1;
                if (i1 > widthMinus1)
                    i1 = widthMinus1;
                int i2 = x - radius;
                if (i2 < 0)
                    i2 = 0;
                int rgb1 = in[inIndex + i1];
                int rgb2 = in[inIndex + i2];

                ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff);
                tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16;
                tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8;
                tb += (rgb1 & 0xff) - (rgb2 & 0xff);
                outIndex += height;
            }
            inIndex += width;
        }
    }

    public int clamp(int x, int a, int b) {
        return (x < a) ? a : (x > b) ? b : x;
    }


    public Bitmap overlay(Bitmap bitmap) {
        bitmap = squareImage(bitmap);
        if (bitmap == null) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        if (width == 0 || height == 0) {
            return null;
        }
        float rota = 330;
        double radians = Math.toRadians(rota);
        /* after rotate , the new width is the original width */
        int rotateWidth = (int) (width / (Math.abs(Math.sin(radians)) + Math
                .abs(Math.cos(radians))));
        int delta = (width - rotateWidth) / 2;

        // result
        Bitmap result = Bitmap.createBitmap(width, width, Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        // foreground
        Bitmap foreBmp = resizeImage(bitmap, rotateWidth, rotateWidth, true);
        // rotate
        Matrix matrix = new Matrix();
        matrix.postRotate(rota);
        Bitmap rotate = Bitmap.createBitmap(foreBmp, 0, 0, rotateWidth,
                rotateWidth, matrix, true);
        canvas.drawBitmap(rotate, 0, 0, null);
        canvas.drawBitmap(foreBmp, delta, delta, null);
        return result;
    }

#End If



Sub FitCenterBitmap(Imv As ImageView, Dir As String, FileName As String, Mode As Int)
    Private bmp As Bitmap = LoadBitmap(Dir, FileName)
    Private cvs As Canvas
    cvs.Initialize(Imv)

    Dim rectDest, rectSource As Rect
    Dim delta As Int
    Select Mode
        Case 1
            If bmp.Width / bmp.Height > Imv.Width / Imv.Height Then
                delta = (Imv.Height - bmp.Height / bmp.Width * Imv.Width) / 2
                rectDest.Initialize(0, delta,Imv.Width, Imv.Height - delta)
            Else
                delta = (Imv.Width - bmp.Width / bmp.Height * Imv.Height) / 2
                rectDest.Initialize(delta, 0, Imv.Width - delta, Imv.Height)
            End If
            cvs.DrawBitmap(bmp, Null, rectDest)
        Case 2
            rectDest.Initialize(0, 0,Imv.Width, Imv.Height)
            If bmp.Width / bmp.Height > Imv.Width / Imv.Height Then
                delta = (bmp.Width - Imv.Width / Imv.Height * bmp.Height) / 2
                rectSource.Initialize(delta, 0,bmp.Width - delta, bmp.Height)
            Else
                delta = (bmp.Height - Imv.Height / Imv.Width * bmp.Width) / 2
                rectSource.Initialize(0, delta, bmp.Width, bmp.Height - delta)
            End If
            cvs.DrawBitmap(bmp, rectSource, rectDest)
    End Select

    Imv.Invalidate
End Sub


First load image to imageview and fit center with function FitCenterBitmap
then save this image with canvase
again load this image to imageview with java corner redius with border function
 
Upvote 0
Top