自定义正方形圆角

在最近的机顶盒媒体中心开发中,遇到这样一个需求


需要将每张图片展示为正方形,并且拥有圆角。所以先将图片裁剪为正方形,再画出圆角
布局:

<ImageView
android:id="@+id/iv"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="94dp"
android:scaleType="centerCrop"/>
android:id="@+id/btn"
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#16e2c7"
android:text="show"/>

将bitmap裁剪为正方形

    public staticBitmapgetRoundCornerImage(Bitmap bitmap, intmRadius, ImageView imageView) {
        intwith = imageView.getWidth();
        intheight = imageView.getHeight();
        intbwith = bitmap.getWidth();
        intbheight = bitmap.getHeight();
        intsw = 0;
        intsh = 0;
        intew = 0;
        inteh = 0;
        Bitmap roundConcerImage = null;
        if (bheight == bwith) {
            roundConcerImage = bitmap;
        } else {
            if (bheight > bwith) {
                sw = 0;
                //裁剪图片中间部位
                sh = (bheight - bwith) / 2;
                ew = bwith;
                eh = bwith;
            } else {
                sh = 0;
                sw = (bwith - bheight) / 2;
                ew = bheight;
                eh = bheight;
            }
            //创建一个正方形的Bitmap
            roundConcerImage = Bitmap.createBitmap(bitmap, sw, sh, ew, eh);
        }
        roundConcerImage = Bitmap.createScaledBitmap(roundConcerImage, with, height, true);
            //画出圆角
        returncreateRoundConerImage(roundConcerImage, mRadius);
    }

    private staticBitmapcreateRoundConerImage(Bitmap source, intmRadius) {
        finalPaint paint = newPaint();
        // 去锯齿
        paint.setAntiAlias(true);
        // 创建一个和原始图片一样大小位图
        Bitmap target = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = newCanvas(target);
        // 创建一个和传入图片一样大小的矩形
        RectF rect = newRectF(0, 0, source.getWidth(), source.getHeight());
        // 画一个和原始图片一样大小的圆角矩形
        canvas.drawRoundRect(rect, mRadius, mRadius, paint);
        // 设置相交模式 取两者相交的部位
        paint.setXfermode(newPorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        // 把图片画到矩形去
        canvas.drawBitmap(source, 0, 0, paint);
        returntarget;
    }

在onCreate中调用方法

iv= (ImageView) findViewById(R.id.iv);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View v) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.img);
Bitmap roundCornerImage =getRoundCornerImage(bitmap,7,iv);
iv.setImageBitmap(roundCornerImage);
}
});

实际效果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容