cari

Rumah  >  Soal Jawab  >  teks badan

Android 设计一个菱形形状的Imageview组件.

网上没有资料,特来请教下大神

巴扎黑巴扎黑2773 hari yang lalu537

membalas semua(4)saya akan balas

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:51:03

    大致思路:自定义view,先画矩形(drawRect),然后cavas旋转(rotate),再画图片,最后做XOR操作:

    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_ATOP));

    balas
    0
  • 黄舟

    黄舟2017-04-17 17:51:03

    可以看看关于PorterDuffXfermode的使用 https://segmentfault.com/a/11...

    balas
    0
  • PHP中文网

    PHP中文网2017-04-17 17:51:03

    Paint.drawPath

    参考:多边形ImageView

    balas
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:51:03

    使用PorterDuffXfermode, 可以看看图像合成Xfermode和任意形状ImageView

    public class RectImageView extends ImageView {
        private Paint mPaint;
        private Xfermode mXfermode;
        private Bitmap mRectMask;
    
        public RectImageView(Context context) {
            this(context, null);
        }
    
        public RectImageView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public RectImageView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setColor(Color.RED);
            // 关键方法
            mXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            createMask();
        }
    
        private void createMask() {
            if (mRectMask == null) {
                int maskWidth = getMeasuredWidth();
                int maskHeight = getMeasuredHeight();
                mRectMask = Bitmap.createBitmap(maskWidth, maskHeight, Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(mRectMask);
                canvas.translate(maskWidth / 2, 0);
                canvas.rotate(45);
                int rectSize = (int) (maskWidth / 2 / Math.sin(Math.toRadians(45)));
                canvas.drawRect(0, 0, rectSize, rectSize, mPaint);
            }
        }
    
    
        @Override
        protected void onDraw(Canvas canvas) {
            int id = canvas.saveLayer(0, 0, canvas.getWidth(), canvas.getHeight(), null, Canvas.ALL_SAVE_FLAG);
            super.onDraw(canvas);
            // 关键方法
            mPaint.setXfermode(mXfermode);
            canvas.drawBitmap(mRectMask, 0, 0, mPaint);
            mPaint.setXfermode(null);
            canvas.restoreToCount(id);
        }
    }

    效果如下

    balas
    0
  • Batalbalas