我正在尝试在ImageView中填充一个圆圈(除圆圈轮廓以外的透明)。
我的代码有效:
public void setPercentage(int p) {
if (this.percentage != p ) {
this.percentage = p;
this.invalidate();
}
}
@Override public void onDraw(Canvas canvas) {
Canvas tempCanvas;
Paint paint;
Bitmap bmCircle = null;
if (this.getWidth() == 0 || this.getHeight() == 0 )
return ; // nothing to do
mergedLayersBitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
tempCanvas = new Canvas(mergedLayersBitmap);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setFilterBitmap(false);
bmCircle = drawCircle(this.getWidth(), this.getHeight());
tempCanvas.drawBitmap(bmCircle, 0, 0, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
tempCanvas.clipRect(0,0, this.getWidth(), (int) FloatMath.floor(this.getHeight() - this.getHeight() * ( percentage/100)));
tempCanvas.drawColor(0xFF660000, PorterDuff.Mode.CLEAR);
canvas.drawBitmap(mergedLayersBitmap, null, new RectF(0,0, this.getWidth(), this.getHeight()), new Paint());
canvas.drawBitmap(mergedLayersBitmap, 0, 0, new Paint());
}
static Bitmap drawCircle(int w, int h) {
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(drawColor);
c.drawOval(new RectF(0, 0, w, h), p);
return bm;
}
它有点工作。但是,我有两个问题:我快速耗尽内存并且GC变得疯狂。如何利用最少的内存进行此操作?
我知道我不应该在onDraw中实例化对象,但是我不确定在哪里绘制。谢谢。
答案 0 :(得分:2)
伪看起来像这样。
for each pixel inside CircleBitmap {
if (pixel.y is < Yboundary && pixelIsInCircle(pixel.x, pixel.y)) {
CircleBitmap .setPixel(x, y, Color.rgb(45, 127, 0));
}
}
可能很慢,但它会起作用,圆圈越小它就越快。
只知道基础知识,位图宽度和高度,例如256x256,圆圈半径,并使事情变得简单,使圆圈居中于128,128。然后,当你逐个像素地去,检查像素X和Y,看它是否落在圆圈内,并在Y极限线下面。
然后使用:
CircleBitmap .setPixel(x, y, Color.rgb(45, 127, 0));
编辑:为了加快速度,甚至不用费心去查看Y限制以上的像素。
答案 1 :(得分:2)
如果您想查看其他解决方案(可能更干净),请查看此链接,filling a circle gradually from bottom to top android