zoukankan      html  css  js  c++  java
  • Android圆角图片汇总

    今天来对图片的圆角处理做一个简单小结,很多app里面都有圆角效果,根据不同的场景可以采用不同的方案,目前来说有三种方案是比较常用的

    方案一 .9.png

    应用场景:1.目标图片已知;2.针对布局背景;

    实现:

    .9.png是最简单的方法,只需要用draw9patch准备好相应的.9图,设置为控件的背景即可.

    参考:http://developer.android.com/tools/help/draw9patch.html

    方案二 剪裁Bitmap

    应用场景:1.图片事先无法预知;2.图片不是非常大 + 方案一场景

    实现:

    这里的剪裁指的是根据原图我们自己生成一张新的bitmap,这个时候指定图片的目标区域为一个圆角局域。这种做法有一点需要生成一个新的bitmap,所以会消耗至少2倍的图片内存,

    下面分析一下代码的含义:

    a.首先创建一个指定高宽的bitmap,作为输出的内容,

    b.然后创建一个相同大小的矩形,利用画布绘制时指定圆角角度,这样画布上就有了一个圆角矩形。

    c.最后就是设置画笔的剪裁方式为Mode.SRC_IN,将原图叠加到画布上,

    这样输出的bitmap就是原图在矩形局域内的内容。

      public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
     
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = 12;
     
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
     
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
     
        return output;
      }
    

    参考:http://ruibm.com/?p=184

    方案三 直接绘制圆角bitmap

    应用场景:同方案二

    这个写法是android team的成员写出来的,特点就是不用不需要额外在创建一个图片,这里把原图构造成了一个BitmapShader,然后就可以用画布直接画出圆角的内容

    BitmapShader shader;shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

    Paint paint = new Paint();

    paint.setAntiAlias(true);

    paint.setShader(shader);

    RectF rect = new RectF(0.0f, 0.0f, width, height);

    // rect contains the bounds of the shape

    // radius is the radius in pixels of the rounded corners

    // paint contains the shader that will texture the shape

    canvas.drawRoundRect(rect, radius, radius, paint);

    参考:http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/

  • 相关阅读:
    2019年8月20日 item系列
    变量和字符
    python命名规则
    五大常用算法之贪心算法
    过河卒
    组成三位数
    编码问题
    FatMouse' Trade
    A Boring Game
    螺旋矩阵
  • 原文地址:https://www.cnblogs.com/avenwu/p/3513498.html
Copyright © 2011-2022 走看看