ImageView rounded corners

后端 未结 17 1849
长发绾君心
长发绾君心 2020-11-27 15:33

I wanted image to have rounded corners. I implement this xml code and use this in my image view. but image overlap the shape. I am downloading the image through async task.<

相关标签:
17条回答
  • 2020-11-27 16:10

    Use this Custom ImageView in Xml

    public class RoundedCornerImageView extends ImageView {
    
        public RoundedCornerImageView(Context ctx, AttributeSet attrs) {
            super(ctx, attrs);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            Drawable drawable = getDrawable();
            if (drawable == null) {
                return;
            }
    
            if (getWidth() == 0 || getHeight() == 0) {
                return;
            }
            Bitmap b = ((BitmapDrawable) drawable).getBitmap();
            Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
            int w = getWidth(), h = getHeight();
            Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);
            canvas.drawBitmap(roundBitmap, 0, 0, null);
        }
    
        public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
            Bitmap finalBitmap;
            if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
                finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                        false);
            else
                finalBitmap = bitmap;
            Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                    finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
    
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                    finalBitmap.getHeight());
    
            final RectF rectf = new RectF(0, 0, finalBitmap.getWidth(),
                    finalBitmap.getHeight());
    
            paint.setAntiAlias(true);
            paint.setFilterBitmap(true);
            paint.setDither(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(Color.parseColor("#BAB399"));
            //Set Required Radius Here
            int yourRadius = 7;
            canvas.drawRoundRect(rectf, yourRadius, yourRadius, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(finalBitmap, rect, rect, paint);
    
            return output;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-27 16:13

    its simple as possible by using this util method

    /*
     * param@ imageView is your image you want to bordered it
     */
    public static Bitmap generateBorders(ImageView imageView){
        Bitmap mbitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        Bitmap imageRounded = Bitmap.createBitmap(mbitmap.getWidth(), mbitmap.getHeight(), mbitmap.getConfig());
        Canvas canvas = new Canvas(imageRounded);
        Paint mpaint = new Paint();
        mpaint.setAntiAlias(true);
        mpaint.setShader(new BitmapShader(mbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        canvas.drawRoundRect((new RectF(0, 0, mbitmap.getWidth(), mbitmap.getHeight())), 100, 100, mpaint);// Round Image Corner 100 100 100 100
        return imageRounded;
    }
    

    then set your image view bitmap with returned value have fun

    0 讨论(0)
  • 2020-11-27 16:13

    Your MainActivity.java is like this:

    LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
    ImageView iv = (ImageView) findViewById(R.id.iv);
    

    You should to first get your image from Resource as Bitmap or Drawable.

    If get as Bitmap:

    Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ash_arrow);
    bm = new Newreza().setEffect(bm, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
    iv.setImageBitmap(bm);
    

    Or if get as Drawable:

    Drawable d = getResources().getDrawable(R.drawable.ash_arrow);
    d = new Newreza().setEffect(d, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
    iv.setImageDrawable(d);
    

    Then create new file as Newreza.java near MainActivity.java, and copy bottom codes in Newreza.java:

    package your.package.name;
    import android.content.res.Resources;
    import android.graphics.Bitmap;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.Drawable;
    //Telegram:@newreza
    //mail:newreza7@gmail.com
    public class Newreza{
        int a,x,y;
        float bmr;
        public Bitmap setEffect(Bitmap bm,float radius,int color){
            bm=bm.copy(Bitmap.Config.ARGB_8888,true);
            bmr=radius*bm.getWidth();
            for(y=0;y<bmr;y++){
                a=(int)(bmr-Math.sqrt(y*(2*bmr-y)));
                for(x=0;x<a;x++){
                    bm.setPixel(x,y,color);
                }
            }
            for(y=0;y<bmr;y++){
                a=(int)(bm.getWidth()-bmr+Math.sqrt(y*(2*bmr-y)));
                for(x=a;x<bm.getWidth();x++){
                    bm.setPixel(x,y,color);
                }
            }
            for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
                a=(int)(bm.getWidth()-bmr+Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
                for(x=a;x<bm.getWidth();x++){
                    bm.setPixel(x,y,color);
                }
            }
            for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
                a=(int)(bmr-Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
                for(x=0;x<a;x++){
                    bm.setPixel(x,y,color);
                }
            }
            return bm;
        }
        public Drawable setEffect(Drawable d,float radius,int color){
            return new BitmapDrawable(Resources.getSystem(),setEffect(((BitmapDrawable)d).getBitmap(),radius,color));
        }
    }
    

    Just notice that replace your package name with first line in the code.

    It %100 works, because is written in details :)

    0 讨论(0)
  • 2020-11-27 16:15

    Now we no need to use any third party lib or custom imageView

    Now We can use ShapeableImageView

    SAMPLE CODE

    First add below dependencies in your build.gradle file

    implementation 'com.google.android.material:material:1.2.0-alpha05'
    

    Make ImageView Circular from coding

    Add ShapeableImageView in your layout

    <com.google.android.material.imageview.ShapeableImageView
        android:id="@+id/myShapeableImageView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/nilesh" />
    

    Kotlin code to make ImageView Circle

    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import com.google.android.material.shape.CornerFamily
    import kotlinx.android.synthetic.main.activity_main.*
    
    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
    
    //        <dimen name="image_corner_radius">50dp</dimen>
    
            val radius = resources.getDimension(R.dimen.image_corner_radius)
            myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
                .toBuilder()
                .setTopRightCorner(CornerFamily.ROUNDED, radius)
                .setTopLeftCorner(CornerFamily.ROUNDED, radius)
                .setBottomLeftCorner(CornerFamily.ROUNDED, radius)
                .setBottomRightCorner(CornerFamily.ROUNDED, radius)
                .build()
    
                // or  You can use setAllCorners() method
    
            myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
                .toBuilder()
                .setAllCorners(CornerFamily.ROUNDED, radius)
                .build()
    
    
        }
    }
    

    OUTPUT

    Make ImageView Circle from using a style

    First, create a below style in your style.xml

    <style name="circleImageViewStyle" >
        <item name="cornerFamily">rounded</item>
        <item name="cornerSize">50%</item>
    </style>
    

    Now use that style in your layout like this

    <com.google.android.material.imageview.ShapeableImageView
        android:id="@+id/myShapeableImageView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="20dp"
        app:shapeAppearanceOverlay="@style/circleImageViewStyle"
        app:srcCompat="@drawable/nilesh" />
    

    OUTPUT

    Please find the complete exmaple here how to use ShapeableImageView

    0 讨论(0)
  • 2020-11-27 16:20

    NEW ANSWER Use Glide library for this. This lib is also recommended by Google. See How to round an image with Glide library?

    OLD ANSWER Just add that image in a cardView and set cardView's elevation on 0dp...will do the trick (in my case was a viewPager with images - just replace the viewPager with an ImageView):

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="250dp"
        app:cardElevation="0dp">
    
        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </android.support.v7.widget.CardView>
    
    0 讨论(0)
  • 2020-11-27 16:21

    SIMPLEST APPROACH:

    Create an xml file rounded_fg.xml under res/drawable/ folder of your app. The content of rounded_fg.xml is as follows,

    <?xml version="1.0" encoding="UTF-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:innerRadiusRatio="2"
        android:shape="ring"
        android:thicknessRatio="1"
        android:useLevel="false">
        <gradient
            android:type="radial"
            android:gradientRadius="8dp"
            android:endColor="@color/white"
           />
    </shape>
    

    You can match endColor with ImageView container layout background & gradientRadius may be any value as per your requirements (<=36dp).

    Now use this drawable as foreground for your imageview as follows,

     <ImageView
         android:layout_width="55dp"
         android:layout_height="55dp" 
         android:foreground="@drawable/rounded_fg" />
    

    Works perfect with square images and/or imageview.

    Square Image/ImageView:

    Rectangular Image/ImageView:

    Foreground applied over a button:

    0 讨论(0)
提交回复
热议问题