【问题标题】:How to draw a bitmap from sdcard to custom ondraw method如何从 sdcard 到自定义 ondraw 方法绘制位图
【发布时间】:2013-03-21 07:01:32
【问题描述】:

我在 sdcard 上有一个图像,谁能告诉我如何将图像从 sdcard 绘制到自定义的 ondraw 方法上

【问题讨论】:

标签: android image canvas sd-card


【解决方案1】:

我得到的答案实际上是从 sdcard 中绘制图像,我们必须在下面的函数中再次初始化图像

      public void surfaceCreated(SurfaceHolder holder)
       {

            ball=BitmapFactory.createScaledBitmap(src,width,height,true);
            bgr=BitmapFactory.decodeFile("/sdcard/1364275090569.jpg");
                }

【讨论】:

    【解决方案2】:

    实际上这是我的代码,在此我可以通过放置在资源文件夹中的图像在背景上绘制和自定义移动图像,但是当我从 sdcard 加载图像然后实现它时,应用程序会给出错误

    public class Preview extends Activity{
    
     BallBounces ball;
     public static int wd;
     public static int ht;
    public static  String txt;
    public static String path;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Intent i=getIntent();
    
        ball = new BallBounces(this);
        setContentView(ball);
    
         txt=i.getStringExtra("bpath");
         path=i.getStringExtra("path");
    
        wd= getWindowManager().getDefaultDisplay().getWidth();
        ht=getWindowManager().getDefaultDisplay().getHeight();
    
    
    
    }
    

    } 类 BallBounces 扩展 SurfaceView 实现 SurfaceHolder.Callback {

    private int mActivePointerId = INVALID_POINTER_ID;
    private static final int INVALID_POINTER_ID = -1;
    private ScaleGestureDetector mScaleDetector;
    private float mScaleFactor = 1.f;
    public float mPosX=0;
    public float mPosY=0;
    public float mLastTouchX;
    public float mLastTouchY;
    
    //For Fetching image
    private Bitmap bmp;
    private Drawable image;
    private byte[] byteArray;
    private ByteArrayBuffer baf = null;
    int wid =Preview.wd, hght = Preview.ht;
    //For Rotation
    int direction = 0;
    int degree = 0;
    String twxt=Preview.txt;
    String pth=Preview.path;
    float wdth,hgt;
    private float newX ;
    public float newY ;
    private float rotateX;
    private float rotateY;
    private float imgX;
    private float imgY;
     GameThread thread;
    public int screenW; //Device's screen width.
    public int screenH; //Devices's screen height.
    public int ballX; //Ball x position.
    public  int ballY; //Ball y position.
    int initialY ;
    float dY; //Ball vertical speed.
    int ballW;
    int ballH;
    int bgrW;
    int bgrH;
    int angle;
    int bgrScroll;
    int dBgrY; //Background scroll speed.
    float acc;
    Bitmap ball, bgr, bgrReverse;
    boolean reverseBackroundFirst;
    boolean ballFingerMove;
    Bitmap d;
    //Measure frames per second.
    long now;
    int framesCount=0;
    int framesCountAvg=0;
    long framesTimer=0;
    Paint fpsPaint=new Paint();
    
    //Frame speed
    long timeNow;
    long timePrev = 0;
    long timePrevFrame = 0;
    long timeDelta;
    
    
    
    
    public BallBounces(Context context) {
        super(context);
    
    
    
        ball = BitmapFactory.decodeResource(getResources(), R.drawable.bubble);//load image
       bgr = BitmapFactory.decodeResource(getResources(), R.drawable.grd); //Load a background.
    
        bgrW = bgr.getWidth();
        bgrH = bgr.getHeight();
    
        ballW = ball.getWidth();
        ballH = ball.getHeight();
    
    
    
        image =new BitmapDrawable(context.getResources() , ball);
    
        imgX=image.getIntrinsicWidth();
        imgY=image.getIntrinsicHeight();
    
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener()); 
        //Set thread
        getHolder().addCallback(this);
    
        setFocusable(true);
    }
    
    @Override
    public void onSizeChanged (int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //This event-method provides the real dimensions of this custom view.
        screenW = w;
        screenH = h;
        System.out.println(w+"  X  "+h);
       bgr = Bitmap.createScaledBitmap(bgr, w, h, true); //Scale background to fit the screen.
        bgrW = bgr.getWidth();
       bgrH = bgr.getHeight();
    
    
    }
    
    //***************************************
    //*************  TOUCH  *****************
    //***************************************
    @Override
    public synchronized boolean onTouchEvent(MotionEvent ev) {
    
         mScaleDetector.onTouchEvent(ev);
    
            final int action = ev.getActionMasked();
    
            if (action == MotionEvent.ACTION_DOWN) {
    
    
                System.out.println("DOWN");
                final float x = ev.getX();
                final float y = ev.getY();
    
                mLastTouchX = x;
                mLastTouchY = y;
    
                System.out.println("DOWN-POSITION--"+x+"  X  "+y);
                mActivePointerId = ev.getPointerId(0); 
            }
    
            if (action == MotionEvent.ACTION_MOVE) {
    
                System.out.println("MOVE");
                final int pointerIndex = ev.findPointerIndex(mActivePointerId);
                final float x = ev.getX(pointerIndex);
                final float y = ev.getY(pointerIndex);
    
                System.out.println("Moving points" +x+" X "+y);
    
                if (!mScaleDetector.isInProgress()) {
                    final float dx = x - mLastTouchX;
    
                    final float dy=y-mLastTouchY;
    
                    mPosX += dx;
                    mPosY += dy;
                    newX=ev.getRawX();
                    newY=ev.getRawY();
    
                    System.out.println("Image Config" +newX+"  X  "+newY);
                    invalidate();
                }
    
                mLastTouchX = x;
                mLastTouchY = y;
    
    
    
            }
    
            if (action == MotionEvent.ACTION_UP) {
                System.out.println("UP");
                mActivePointerId = INVALID_POINTER_ID;
    
    
            }
    
            if (action == MotionEvent.ACTION_CANCEL) {
                System.out.println("CANCEL");
                mActivePointerId = INVALID_POINTER_ID;
            }
    
            if (action == MotionEvent.ACTION_POINTER_UP) {
                System.out.println("ACTN_POINTER_UP");
                final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) 
                >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
    
            }
    
            return true;
    }
    
    public BitmapDrawable writeOnDrawable(int drawableId, String text){
    
    
    
        Rect bounds = new Rect();
        Paint textPaint = new Paint();
        textPaint.getTextBounds(twxt,0,twxt.length(),bounds);
        float height = bounds.height();
        float width = bounds.width();
        wdth=width/2;
        hgt=height/2;
    
        Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
    
        Paint paint = new Paint(); 
        paint.setStyle(Style.FILL_AND_STROKE);  
        paint.setColor(Color.WHITE);
    
        paint.setTextSize(15); 
        Canvas canvas = new Canvas(bm);
        int xPos =(int) ((bm.getWidth()/2)-wdth);
    
        int yPos = (int) ((bm.getHeight()/2)-hgt) ;
    
        canvas.drawText(text, xPos-(wdth/8),yPos+hgt, paint);
        return new BitmapDrawable(bm);
    }
    
    
    
    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Rect fromRect1 = new Rect(0, 0, bgrW - bgrScroll, bgrH);
        Rect toRect1 = new Rect(bgrScroll, 0, bgrW, bgrH);
    
        Rect fromRect2 = new Rect(bgrW - bgrScroll, 0, bgrW, bgrH);
        Rect toRect2 = new Rect(0, 0, bgrScroll, bgrH);
    
        if (!reverseBackroundFirst) {
            canvas.drawBitmap(bgr, fromRect1, toRect1, null);
    
        }
        else{
            canvas.drawBitmap(bgr, fromRect2, toRect2, null);
    
        }
    
    
       if(mPosX<0)
        {
            mPosX=0;
        }
        if(mPosX>screenW-ballW)
        {
            mPosX=screenW-ballW;
        }
        if(mPosY>screenH-ballH)
        {
            mPosY=screenH-ballH;
        }
    
        if(mPosY<0)
        {
            mPosY=0;
        }
    
        canvas.drawBitmap(ball, mPosX, mPosY, null); 
         canvas.drawText(mPosX+ "  X  "+mPosY, 40, 70, fpsPaint);
         canvas.drawText(ballW+ "  X  "+ballH, 40, 100, fpsPaint); 
    
         canvas.drawText(screenW+ "  X  "+screenH, 40, 150, fpsPaint);
    }
    
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }
    
    
    
    public void surfaceCreated(SurfaceHolder holder) {
        thread = new GameThread(getHolder(), this);
        thread.setRunning(true);
        thread.start();
    }
    public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;
        thread.setRunning(false);
        while (retry) {
            try {
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
    
            }
        }
    }
    
    
    class GameThread extends Thread {
        private SurfaceHolder surfaceHolder;
        private BallBounces gameView;
        private boolean run = false;
    
        public GameThread(SurfaceHolder surfaceHolder, BallBounces gameView) {
            this.surfaceHolder = surfaceHolder;
            this.gameView = gameView;
        }
    
        public void setRunning(boolean run) {
            this.run = run;
        }
    
        public SurfaceHolder getSurfaceHolder() {
            return surfaceHolder;
        }
    
        @Override
        public void run() {
            Canvas c;
            while (run) {
                c = null;
    
                //limit frame rate to max 60fps
                timeNow = System.currentTimeMillis();
                timeDelta = timeNow - timePrevFrame;
                if ( timeDelta < 16) {
                    try {
                        Thread.sleep(16 - timeDelta);
                    }
                    catch(InterruptedException e) {
    
                    }
                }
                timePrevFrame = System.currentTimeMillis();
    
                try {
                    c = surfaceHolder.lockCanvas(null);
                    synchronized (surfaceHolder) {
                       //call methods to draw and process next fame
                        gameView.onDraw(c);
                    }
                } finally {
                    if (c != null) {
                        surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
    
    
    
    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();
    
            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
    
            invalidate();
            return true;
        }
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      相关资源
      最近更新 更多