当我对PaintView
进行充气时,它有时会显示OutOfMemoryException
。我使用位图来刮擦图像,并根据我调整图像的大小。
这是我的代码:
public class PaintView extends View implements OnTouchListener {
Bitmap Bitmap1, Bitmap2;
Bitmap Transparent;
Bitmap overlay;
int X = -100;
int Y = -100;
Canvas c2;
private boolean isTouched = false;
// List<Point> points = new ArrayList<Point>();
Paint paint = new Paint();
public PaintView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
@SuppressWarnings("static-access")
private void initView(Context context) {
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Transparent = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
/*Bitmap2 = BitmapFactory
.decodeResource(getResources(), R.drawable.main);
*/
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.scratch_image);
/* int width1 = bitmapOrg.getWidth();
int height1 = bitmapOrg.getHeight();
int newWidth = width;
int newHeight = height;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width1;
float scaleHeight = ((float) newHeight) / height1;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
//matrix.postRotate(90);
// this will create image with new size
Bitmap2 = Bitmap.createBitmap(bitmapOrg,bitmapOrg.getWidth(),bitmapOrg.getHeight(),width, height, matrix, true);
*/
Bitmap2=bitmapOrg.createScaledBitmap(bitmapOrg, width, height, true);
c2 = new Canvas();
c2.setBitmap(Transparent);
// c2.drawBitmap(Bitmap1, 0, 0, null);
c2.drawBitmap(Bitmap2, 0, 0, paint);
paint.setAlpha(0);
paint.setStyle(Style.FILL);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
paint.setAntiAlias(true);
}
@Override
public void onDraw(Canvas canvas) {
System.out.println("onDraw");
c2.drawCircle(X, Y, 50, paint);
if(isTouched)
{
canvas.drawBitmap(Bitmap1, 0, 0, null);
}
canvas.drawBitmap(Transparent, 0, 0, null);
}
public boolean onTouch(View view, MotionEvent event) {
isTouched = true;
X = (int) event.getX();
Y = (int) event.getY();
invalidate();
return true;
}
}
class Point {
float x, y;
@Override
public String toString() {
return x + ", " + y;
}
}
这是我的xml:
<com.test.test.lottery.PaintView
android:id="@+id/img1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />