Skip to content

Instantly share code, notes, and snippets.

@AssIstne
Last active April 5, 2017 08:20
Show Gist options
  • Save AssIstne/c9f62d7e22669748da7ccae1ae5a3abf to your computer and use it in GitHub Desktop.
Save AssIstne/c9f62d7e22669748da7ccae1ae5a3abf to your computer and use it in GitHub Desktop.
图像合成Xfermode和任意形状ImageView的示例代码 http://www.jianshu.com/p/96c2bfc4f33a
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* 图像合成Xfermode和任意形状ImageView的示例代码
* http://www.jianshu.com/p/96c2bfc4f33a
* 注: 在边长计算中假设了`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.ALPHA_8);
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment