我需要产生以圆形绘制位图的效果,这个圆圈将从中心生长,直到达到最大半径为止,为此,我编写了以下方法:
public Bitmap applyDrawingEffect(Bitmap src, int nRadiusprct)
{
// image size
int width = src.getWidth();
int height = src.getHeight();
// create bitmap output
Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// set canvas for painting
Canvas canvas = new Canvas(result);
canvas.drawARGB(0, 0, 0, 0);
// config paint
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
// config rectangle for embedding
final Rect rect = new Rect(0, 0, width, height);
final RectF rectF = new RectF(rect);
// draw rect to canvas
//canvas.drawRoundRect(rectF, round, round, paint);
float fRadius = (width<=height) ? (width/2) : (height/2);
canvas.drawCircle(width/2, height/2, (fRadius * nRadiusprct/100), paint);
// create Xfer mode
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// draw source image to canvas
canvas.drawBitmap(src, rect, rect, paint);
// return final image
return result;
}
如您所见,我将半径百分比作为参数传递,我的问题是如何越来越多地优化代码,为什么我需要每次都创建一个位图并将其分配给新的画布实例并再次重新绘制.. ..
有没有办法创建一个位图并多次绘制它以产生相同的效果。
答案 0 :(得分:0)
对于使用画布和位图的简单方法,您可以将它与一个Androids动画方法一起使用来完成繁重的工作。下面我使用值animator编写了一个翻译动画,用于在画布内移动我的位图。它并不需要一遍又一遍地重新创建位图。
public void doCanvas(){
//Create our resources
Bitmap bitmap = Bitmap.createBitmap(mLittleChef.getWidth(), mLittleChef.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
final Bitmap chefBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.dish_special);
final Bitmap starBitmap= BitmapFactory.decodeResource(getResources(),R.drawable.star);
//Link the canvas to our ImageView
mLittleChef.setImageBitmap(bitmap);
ValueAnimator animation= ValueAnimator.ofInt(canvas.getWidth(),0,canvas.getWidth());
animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int value = (Integer) animation.getAnimatedValue();
//Clear the canvas
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.drawBitmap(chefBitmap, 0, 0, null);
canvas.save();
canvas.translate(value,0);
canvas.drawBitmap(starBitmap, 0, 0, null);
canvas.restore();
//Need to manually call invalidate to redraw the view
mLittleChef.invalidate();
}
});
animation.addListener(new AnimatorListenerAdapter(){
@Override
public void onAnimationEnd(Animator animation) {
simpleLock= false;
}
});
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(mShortAnimationDuration);
animation.start();
}
有关代码和画布的更多信息,以及使用canvas和bitmap的不同方式,请参阅 here