Tuesday 28 January 2014

Circular image and imageview in android

Here is the procedure to create circular image in android:

First method:

Bitmap bitmap = get some bitmap image;
     
       
        if(bitmap!=null)
       
        {
   
   int targetWidth = 65;
   int targetHeight = 65;
   Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,Bitmap.Config.ARGB_8888);
   BitmapShader shader;
   shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

   Paint paint = new Paint();
   paint.setAntiAlias(true);
   paint.setShader(shader);
   Canvas canvas = new Canvas(targetBitmap);
   Path path = new Path();
   path.addCircle(((float) targetWidth - 1) / 2,
   ((float) targetHeight - 1) / 2,
   (Math.min(((float) targetWidth),((float) targetHeight)) / 2),Path.Direction.CCW);
   paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
   paint.setStyle(Paint.Style.STROKE);
   canvas.clipPath(path);
   Bitmap sourceBitmap = bitmap;
   canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),sourceBitmap.getHeight()),
   new Rect(0, 0, targetWidth,targetHeight), null);
 
 
    imageView.setImageBitmap(targetBitmap);   //set the circular image to your imageview
        }
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }




here is the demo:








Another method:


Create Circular imageview:

public class CircularImageView extends ImageView
{
    private int borderWidth = 4;
    private int viewWidth;
    private int viewHeight;
    private Bitmap image;
    private Paint paint;
    private Paint paintBorder;
    private BitmapShader shader;

    public CircularImageView(Context context)
    {
        super(context);
        setup();
    }

    public CircularImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        setup();
    }

    public CircularImageView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        setup();
    }

    @SuppressLint("NewApi")
private void setup()
    {
        // init paint
        paint = new Paint();
        paint.setAntiAlias(true);

        paintBorder = new Paint();
        setBorderColor(Color.GREEN);
        paintBorder.setAntiAlias(true);
        this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
        paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
    }

    public void setBorderWidth(int borderWidth)
    {
        this.borderWidth = borderWidth;
        this.invalidate();
    }

    public void setBorderColor(int borderColor)
    {
        if (paintBorder != null)
            paintBorder.setColor(borderColor);

        this.invalidate();
    }

    private void loadBitmap()
    {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();

        if (bitmapDrawable != null)
            image = bitmapDrawable.getBitmap();
    }

    @Override
    public void onDraw(Canvas canvas)
    {
        // load the bitmap
        loadBitmap();

       
        if (image != null)
        {
            shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            paint.setShader(shader);
            int circleCenter = viewWidth / 2;

         
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - 4.0f, paintBorder);
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - 4.0f, paint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec, widthMeasureSpec);

        viewWidth = width - (borderWidth * 2);
        viewHeight = height - (borderWidth * 2);

        setMeasuredDimension(width, height);
    }

    private int measureWidth(int measureSpec)
    {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY)
        {
            // We were told how big to be
            result = specSize;
        }
        else
        {
            // Measure the text
            result = viewWidth;
        }

        return result;
    }

    private int measureHeight(int measureSpecHeight, int measureSpecWidth)
    {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpecHeight);
        int specSize = MeasureSpec.getSize(measureSpecHeight);

        if (specMode == MeasureSpec.EXACTLY)
        {
            result = specSize;
        }
        else
        {
            result = viewHeight;
        }

        return (result + 2);
    }
}


And call the class in your layout:

<com.newapplication.CircularImageView
    android:id="@+id/row_icon"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="22dp"
    android:contentDescription="@string/app_name"
    android:padding="10dp"
    android:scaleType="fitCenter"
    android:src="@drawable/peacock" />

42 comments:

Unknown said...

Shader.TileMode.CLAMP
Getting the error of Shader.

Unknown said...

Congratulations guys, quality information you have given!!!..Its really useful blog. Thanks for sharing this useful information..Android Training institute in chennai with placement | Android Training in chennai |Android Training in Velachery | android development course fees in chennai

buy instagram account with 10k followers said...

Thanks for sharing such a nice info with us. Fantastic writing skills. I appreciate this blog.

Does Epilating Hurt said...

I have read your blog its very attractive and impressive.

Vernon said...

Its great to see this post. I really appreciate your work Captain Marvel Jacket

Ella Nike said...

please write in text not in html code everyone cant understand army men corcoran boot

Reviewstook said...

Comment with your Google Account if you’d like to be Kissanime watch online guide able to manage your comments in the future. If you comment anonymously, you won’t be able to edit or delete your comment. Learn more

Reviewstook said...

Comment with your Google Account if you’d like to season 2 of prison school be able to manage your comments in the future. If you comment anonymously, you won’t be able to edit or delete your comment. Learn more

White Canary said...

Thanks for sharing such a great and informative post.

styleup365 said...

nice information here you collect infor about new fashion trend Styleup365.net and enhance your collection.

buzznor said...

here you can get anime movies with hd quality https://buzznor.com/

smm newz said...

you can update your information through Smmnewz.com

WorthGram said...

i give you opportunity to write what you want"write for us"

best electric pressure washer 2019 said...

nice information here you collect info about gogoanimes and enhance your collection.

Cyberpunk 2077 Leather Jacket said...

It's great to see this post. I really appreciate your work

kevin said...

Thanks for sharing such a great and informative post.

danezon.com

Aditya said...

Great post again! Techshop Through with this content, you have given stand out introduction. Appreciate the value

Harry Potter Books said...

welcome to you in my blog full of thril and interest i know there many more people who like harry poter and whant its novels so come to me free of coast online download and read order of harry potter books

Jons said...

Wow, this is very interesting reading Social Magz i found a lot of thing which I need. Great job on this content. I like it.

Buzz Nor said...

This is an unbelievable rousing article.

Jons said...

Great post again! Through with this content, Techno Mention you have given stand out introduction. Appreciate the value

Allegra Versace said...

Thank you to communion more mileposts in the time to come.

Jordi said...

God's Antique Roadshow is a unique title somehow. As a reader i need to post this blog writers per hour sites just to aware the students about the new ideas. I would like to share this blog with others. Rouser News

rokka no yuusha season 2 said...

Such an amazing article keep it up

Read More said...

This article is really fantastic and thanks for sharing the valuable post.

Anonymous said...

firestick channels 2020 Truely satisfied with all the information I have found in this article. It gives immense knowledge on physical education, it is very helpful

Muqbar said...

Search engine optimization (SEO) includes all the strategies which can boost visitors on site. After which search engines increase the ranking of that specific site. Hence, SEO is the method of skyrocketing the standard and quantity of website traffic.

Anonymous said...

Very nice article, I found something more interesting.
9anime

Jons said...

Amazing post great work.
no game no life season 2

charlie said...

its all about seo heartland season 11

charlie said...

satisfied with all the information I have found in this article. It gives immense knowledge on physical education, it is very helpful bibmovies

bobmovies said...

Thank you for taking the time to write and sharing this. I really appreciate your work.

vumoo - RouserNews said...

Thanks for sharing this information it's really helpful.

Tech Markets News said...

This is an Awesome blog post. Thanks for sharing with us. I really appreciate you keep blogging.

Raven Bowman said...

Thanks for sharing such a marvelous post! I truly enjoyed while reading it. I always learn something new from your article. You are the epitome of knowledge. Keep spreading this.

Liza Sengupta said...

You have an amazing blog. The posts are very educational and helpful. You are doing a great job here. Keep posting!
The Global Information Blog publishes insightful Business, Health, Travel, Finance article written by the brightest of the minds from industry verticals. Visit now-
The Global Information - A Blog for Finance, Health, Travel Tips

Priya Gupta said...

I totally love to visit this blog. The information shared here is exceptional and much better than other sites. You should keep writing and sharing more to make this blog the best one can ever find. Good luck mate!
11 Best Cashbacks Credit Cards For Shopping In India 2020-21

cristinajohn said...

Treat your looks with the cool and smart outfit A2 Flight Airforce Jackets with free shipping.

cristinajohn said...

thanks for this wonderful article it was nice and amazing. Thats Cool Baby Jacket

Hosting Live said...

Really impressive post. Thanks for sharing such cool posts!
hostinglive247

Kcthakur058@bloggest said...
This comment has been removed by the author.
Rudy Giuliani Twitter said...

I appreciate the way you have given the complete introduction. I must say it was a great post. Like all other previous work, I loved this one too.