2011-11-13 55 views
4

我正在尝试使用蒙版。 我想用一个图像来暴露底层图像的一部分。 例如我有一个箭头,它暴露了底层(红色)正方形的一部分。 我的问题是,虽然面具的作品,任何未公开的呈现为一个黑色的矩形,而我想要一个透明的背景。我的箭头图像有一个透明的画布。如何在android中使用蒙版

我的代码是:

private class MaskAttempt extends View { 

     private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 

     private Bitmap mItemToBeMasked; 
     private Bitmap mMask; 

     public MaskAttempt(Context context) { 
      super(context); 
      this.setBackgroundColor(Color.WHITE); 
      mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); 

       final Resources res = context.getResources(); 
      mItemToBeMasked = BitmapFactory.decodeResource(res, R.drawable.red_rectangle); 
      mMask = BitmapFactory.decodeResource(res, R.drawable.icon_mask); 
     } 

     @Override 
     protected void onDraw(Canvas canvas) { 
      super.onDraw(canvas); 
      canvas.save(); 

      canvas.translate((getWidth() - mItemToBeMasked.getWidth()) >> 1, (getHeight() -  mItemToBeMasked.getHeight()) >> 1); 

      canvas.drawBitmap(mItemToBeMasked, 0, 0, null); 
      canvas.drawBitmap(mMask, 0, 0, mPaint); 

      canvas.restore(); 
     } 

你可以看到我通过看http://www.steveharris100.pwp.blueyonder.co.uk/

回答

0

意味着你需要添加MaskAttempt一个更Bitmap

public MaskAttempt(Context context) { 
    super(context); 
    this.setBackgroundColor(Color.WHITE); 
    mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); 

    final Resources res = context.getResources(); 
    mItemToBeMasked = BitmapFactory.decodeResource(res, R.drawable.red_rectangle); 
    mMask = BitmapFactory.decodeResource(res, R.drawable.icon_mask); 
    duplicate = BitmapFactory.decodeResource(res, R.drawable.icon_mask).copy(Config.ARGB_8888, true); 

    c = new Canvas(duplicate); 

    x = new Paint(Paint.ANTI_ALIAS_FLAG); 
    x.setColor(Color.BLACK); 
    x.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    canvas.save(); 

    canvas.translate((getWidth() - mItemToBeMasked.getWidth()) >> 1, (getHeight() -  mItemToBeMasked.getHeight()) >> 1); 

    c.drawBitmap(mItemToBeMasked, 0, 0, null); 
    c.drawBitmap(mMask, 0, 0, mPaint); 
    canvas.drawBitmap(duplicate, 0, 0, null); 

    canvas.restore(); 
}