2013-08-29 65 views
7

我試圖在放置爲res/drawable/schoolboard.png的圖像上畫一個圓。圖像填充活動背景。以下不起作用:在現有圖像上畫一個圓圈

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.schoolboard); 
    Paint paint = new Paint(); 
    paint.setAntiAlias(true); 
    paint.setColor(Color.BLUE); 

    Canvas canvas = new Canvas(bitmap); 
    canvas.drawCircle(60, 50, 25, paint); 

    ImageView imageView = (ImageView)findViewById(R.drawable.schoolboard); 
    imageView.setAdjustViewBounds(true); 
    imageView.setImageBitmap(bitmap); 

任何幫助將不勝感激。謝謝。

回答

10

有在你的代碼中的一些錯誤: 第一的事情,你不能給的參考ID爲繪製在findViewById 所以我覺得你的意思是類似的東西

ImageView imageView = (ImageView)findViewById(R.id.schoolboard_image_view); 

schoolboard_image_view在圖片ID您XML佈局(請檢查您的佈局正確的ID)

BitmapFactory.Options myOptions = new BitmapFactory.Options(); 
    myOptions.inDither = true; 
    myOptions.inScaled = false; 
    myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important 
    myOptions.inPurgeable = true; 

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.schoolboard,myOptions); 
    Paint paint = new Paint(); 
    paint.setAntiAlias(true); 
    paint.setColor(Color.BLUE); 


    Bitmap workingBitmap = Bitmap.createBitmap(bitmap); 
    Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true); 


    Canvas canvas = new Canvas(mutableBitmap); 
    canvas.drawCircle(60, 50, 25, paint); 

    ImageView imageView = (ImageView)findViewById(R.id.schoolboard_image_view); 
    imageView.setAdjustViewBounds(true); 
    imageView.setImageBitmap(mutableBitmap); 

請務必使用正確的圖像ID爲:

ImageView imageView =(ImageView)findViewById(R.id.schoolboard_image_view);

+1

謝謝你們倆!改變了xml文件的圖像視圖,因爲在schoolboard圖像被定義爲'android:background =「@ drawable/schoolboard」'在RelativeLayout中。現在它工作! – Kfir

5

首先,您需要創建一個新的位圖,因爲BitmapFactory.decodeResource()方法的位圖是不可變的。您可以使用以下代碼執行此操作:

Bitmap canvasBitmap = Bitmap.createBitmap([bitmap_width], [bitmap_height], Config.ARGB_8888); 

在Canvas構造函數中使用此位圖。然後在畫布上繪製您的位圖。

Canvas canvas = new Canvas(canvasBitmap); 
canvas.drawBitmap(bitmap, 0, 0, bitmapPaint); 
canvas.drawCircle(60, 50, 25, paint); 

此外,R.drawable.schoolboard不是一個正確的視圖ID。

ImageView imageView =(ImageView)findViewById(R.drawable.schoolboard);