开发者

Precise positioning in Android

I am developing an app where I need an image to be positioned precisely at a certain x and y position.The image will randomly be moving to new posi开发者_如何学JAVAtions.

I cannot see how to accomplish this.


Even if android encourages to use layouts for this (since there is several size, dimensions quality resolutions of screens with layouts you'll have the same aspect on all devices).

there is 2 other ways you can do this

1) change everything for an opengl view ^^ but thats taking out a canon to get a mosquito.

2) Create your own view, override the onDraw(canvas) and do your own drawing there.

I have to warn you it get really tedious to get all the drawings position correctly on the Canvas


edit here is some code to get you started on creating your views programatically, I also added the touch test.

(one thing I want to draw your attention: there is a image.getWidth() (actual size of the picture) and a image.getScaledWidth(canvas) which give you the size of the element in dp which means how big it will appear on the screen)

public class MainMenuView extends PixelRainView{
    private Bitmap bmpPlay = null;
    private float playLeft = 0;
    private float playRight = 0;
    private float playBottom = 0;
    private float playTop = 0;

    public MainMenuView(Context context, AttributeSet attrs) {
        super(context,attrs);
    }



    @Override
    public void unLoadBitmaps() {
        super.unLoadBitmaps();
        if(bmpPlay != null){
            bmpPlay.recycle();
            bmpPlay = null;
        }
    }



    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(bmpPlay == null){
            bmpPlay = getBitmapFromRessourceID(R.drawable.play_bt);
            playLeft = (this.getWidth()-bmpPlay.getScaledWidth(canvas))/2; 
            playRight = playLeft + bmpPlay.getScaledWidth(canvas);
            playTop = (this.getHeight()-bmpPlay.getScaledHeight(canvas))/2;
            playBottom = playTop+bmpPlay.getScaledHeight(canvas);
        }
        canvas.drawBitmap(bmpPlay,playLeft, playTop, null);

        }       
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }



    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            float x = event.getX();
            float y = event.getY();
            //test central button
            if(x>playLeft && x<playRight && y<playBottom && y>playTop){
                Log.e("jason", "touched play");
                PixelRainView.changeView(R.layout.composedlayoutgroup);
            }
        return super.onTouchEvent(event);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜