2010-01-31 13 views
18

캔버스에 안드로이드에 객체를 그리는 다른 방법이 있습니까? 무승부 내부캔버스에 객체/이미지 그리기

이 코드는() 작동하지 않습니다 : 음 실제로 내 첫 번째 코드에서 일하고있어하지만 난 MarkOverlay라는 다른 클래스에이 옮겨진 한 때, 그것은 더 이상 작동하지 않습니다

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);

.

이 코드를 작성하려면 MarkerOverlay에 어떤 매개 변수를 전달해야합니까? 오류는 getResources()에 있습니다.

FYI, canvas.drawOval은 완벽하게 작동하지만 실제로 타원형이 아닌 이미지를 그려야합니다.

public class CustomView extends View { 

    private Drawable mCustomImage; 

    public CustomView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     mCustomImage = context.getResources().getDrawable(R.drawable.my_image); 
    } 

    ... 

    protected void onDraw(Canvas canvas) { 
     Rect imageBounds = canvas.getClipBounds(); // Adjust this for where you want it 

     mCustomImage.setBounds(imageBounds); 
     mCustomImage.draw(canvas); 
    } 
} 

답변

22
package com.canvas; 

import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.view.View; 

public class Keypaint extends View { 
    Paint p; 

    @Override 
    protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     p=new Paint(); 
     Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.icon); 
     p.setColor(Color.RED); 
     canvas.drawBitmap(b, 0, 0, p); 
    } 

    public Keypaint(Context context) { 
     super(context); 
    } 
} 
+7

당신은 Bitmap.recycle (비트 맵 데이터)를 확보해야한다 그렇지 않으면 당신은 불쾌한 메모리 누수를 얻을 : :) –

+5

onDraw에서 이미지를 해독하지 마십시오. 렌더링 루프 외부에서 많은 양의 작업을 수행하십시오. – slott

14

나는 단지 이미지를 한 번 생성으로이 작업을 수행하는 것을 선호합니다 : 모든 드로잉주기에 새로운 비트 맵을 생성합니다.
+5

할당을하지 않거나 onDraw에서 이미지를 풀지 않는 경우 +1 – user1532390

+1

은 다음과 같은 경고 메시지를 표시합니다. 그리기 작업 중 객체 할당 방지 : Canvas.getClipBounds() 대신 Canvas.getClipBounds()를 사용하여 임시 Rect를 할당합니다. – oat

+1

이클립스가 제공 한 간단한 옵티 마이저 히트 (optimizer hit)를 따르는 것이 더 좋다. 예. \t \t canvas.getClipBounds (imageBounds); \t \t mCustomImage.setBounds (imageBounds); 매우 빠른 onDraw를 갖는 것이 매우 중요합니다. – slott