通常的图片圆角一般是对单独的图片进行切圆角操作,但是像下图的效果就没那么合适了,虽然对单张图片切圆角也能实现,但更为繁琐、不简洁,因为数据内容是动态的,要根据数据源分很多种情况判断哪张图片该切哪个角。
所以,我在想能不能就在外层容器的四个角切圆角而不用管内部图片的圆角情况呢?答案显然是能!主要思路就是自定义一个layout,在dispatchdraw的时候将数据图片的canvas与圆角bitmap混合,设置xfermode为porterduff.mode.dst_in使交集部分展示即可达到图示的效果
关键代码(根据后台数据生成里面的每个item相关代码没有贴,根据业务场景改变即可):
public class hotcityview extends linearlayout { private linearlayout ll_item_container1, ll_item_container2; private int itemh, itemspace; private int padding; private paint clippaint; private rectf cliprect; private bitmap maskbitmap; private int cornersize; public hotcityview(@nonnull context context) { this(context, null); } public hotcityview(@nonnull context context, @nullable attributeset attrs) { this(context, attrs, 0); } public hotcityview(@nonnull context context, @nullable attributeset attrs, int defstyle) { super(context, attrs, defstyle); setorientation(vertical); inflate(context, r.layout.m_layout_hot_city, this); padding = (int) getresources().getdimension(r.dimen.list_lr_margin1); setpadding(padding, 0, padding, 0); itemh = pixelutil.dp2px(109); itemspace = (int) getresources().getdimension(r.dimen.hot_item_space); cornersize = pixelutil.dp2px(8); ll_item_container1 = findviewbyid(r.id.m_hot_city_item_container1); ll_item_container2 = findviewbyid(r.id.m_hot_city_item_container2); clippaint = new paint(paint.anti_alias_flag); clippaint.setstyle(paint.style.fill); } @override protected void dispatchdraw(canvas canvas) { if (cliprect == null || getmeasuredwidth() == 0) { cliprect = new rectf(padding, 0, getmeasuredwidth() - padding, getmeasuredheight()); maskbitmap = bitmap.createbitmap(canvas.getwidth(), canvas.getheight(), bitmap.config.argb_4444); canvas c = new canvas(maskbitmap); //在蒙版上画需要覆盖的图形 c.drawroundrect(cliprect, cornersize, cornersize, clippaint); } //保存还没有绘制之前的图层 int layerid = canvas.savelayer(cliprect, clippaint, canvas.all_save_flag); //绘制底部图层 super.dispatchdraw(canvas); //设置混合模式,实现view的四个圆角 clippaint.setxfermode(new porterduffxfermode(porterduff.mode.dst_in)); canvas.drawbitmap(maskbitmap, 0, 0, clippaint); clippaint.setxfermode(null); //恢复之前的图层,要不然背景是黑色的 canvas.restoretocount(layerid); } //这种方式也可以实现裁剪效果,但是需要5.0以上 private void cliproundview() { if (android.os.build.version.sdk_int >= android.os.build.version_codes.lollipop) { viewoutlineprovider viewoutlineprovider = new viewoutlineprovider() { @override public void getoutline(view view, outline outline) { //修改outline为特定形状 outline.setroundrect(0, 0, getmeasuredwidth(), getmeasuredheight(), cornersize); } }; //重新设置形状 setoutlineprovider(viewoutlineprovider); //添加背景或者是imageview的时候失效,添加如下设置 setcliptooutline(true); } } }
附各种xfermode的效果(这张图太经典了,按照命名规则其实很容易理解,无需记住,到用的时候查阅即可):
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。