Scale a view and its layered subviews relatively

后端 未结 2 1012
天涯浪人
天涯浪人 2021-01-15 05:46

(This is somewhat a follow-up on Android: How do you scale multiple views together?)

My task is to port an iPhone / iPad app on Android that consists of a simple ima

2条回答
  •  逝去的感伤
    2021-01-15 06:05

    Well, answering my own question - here is the way I resolved the issue:

    1. I placed the background image on the top of my ImageView with ImageView.setScaleType(ScaleType.FIT_START)
    2. I calculated the scale factor of my background image like so:
        WindowManager mgr = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        mgr.getDefaultDisplay().getMetrics(metrics);
        Drawable image = context.getResources().getDrawable(R.drawables.someImage);
        float scale = metrics.widthPixels / (float) image.getIntrinsicWidth();
    
    1. Finally, I used this scale in a custom ImageView class that loads the overlays to position and scale the view properly:
        public class OverlayImage extends ImageView
        {
            private int imgWidth, imgHeight;
            private final float scale;
    
            public OverlayImage(Context context, int xPos, int yPos, float scale)
            {
                super(context);
                this.scale = scale;
    
                LayoutParams animParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT);
                animParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                animParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                animParams.leftMargin = (int) (scale * xPos);
                animParams.topMargin = (int) (scale * yPos);
                setLayoutParams(animParams);
    
                Drawable dr = context.getResources().getDrawable(R.id.someImage);
                setBackgroundDrawable(dr);
                imgWidth = dr.getIntrinsicWidth();
                imgHeight = dr.getIntrinsicHeight();
            }
    
            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
            {
                setMeasuredDimension((int) (scale * imgWidth),
                        (int) (scale * imgHeight));
            }
        }
    

提交回复
热议问题