我有一个带有透明左右部分的可绘制对象。我需要在其中取得一些进展。
startDrawable.setBounds(0, 0, startDrawable.getIntrinsicWidth(), canvas.getHeight());
startDrawable.draw(canvas);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
Path path = new Path();
path.moveTo(0, 0);
path.lineTo(startDrawable.getIntrinsicWidth() / 2, 0);
path.lineTo(startDrawable.getIntrinsicWidth() / 2, canvas.getHeight());
canvas.drawPath(path, paint);
但是不幸的是,这段代码也填充了透明部分,看起来像黑色矩形。
答案 0 :(得分:1)
您可以创建两个不同的位图:
通过这种方式,您可以在普通的矩形/正方形位图中自由绘制所需的内容,最后使用自由形状(三角形,圆形等)应用Mask(在整个Bitmap上)。从原始矩形版本开始,使用相同的技术创建圆形图片。
例如,以下代码创建矩形位图的圆形版本:
@Nullable
public static Bitmap getRoundedBitmap(@Nullable final Bitmap bmp, final int radius) {
if ((bmp == null) || (radius < 1)) return null;
Bitmap cBitmap;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float cSmallest = Math.min(bmp.getWidth(), bmp.getHeight());
float cFactor = cSmallest / radius;
try {
cBitmap = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / cFactor), (int)(bmp.getHeight() / cFactor), true);
} catch (Exception e) {
cBitmap = null;
}
} else cBitmap = bmp;
if (cBitmap == null) return null;
final Bitmap cOutput = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
final Canvas cCanvas = new Canvas(cOutput);
final Paint cPaint = new Paint();
final Rect cRect = new Rect(0, 0, radius, radius);
cPaint.setAntiAlias(true);
cPaint.setFilterBitmap(true);
cPaint.setDither(true);
cPaint.setStyle(Paint.Style.FILL);
cCanvas.drawARGB(0, 0, 0, 0);
cPaint.setColor(Color.BLACK);
cCanvas.drawCircle(radius / 2f, radius / 2f, radius / 2f, cPaint);
cPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//draws the rectangular Bitmap and use the special Paint object that has the circular "mask" set
cCanvas.drawBitmap(cBitmap, cRect, cRect, cPaint);
return cOutput;
}