开发者

Scale images in android relative to screen width

I have a layout with two images:

开发者_运维百科
  • one that should strech to the screen width
  • one above it that should scale to the same proportion the first one was automaticaly scaled (relative to the original image size)

More specific: the two images are slices of the same image, and therefore some details inside them should match.

Can I make this in XML?

If I cannot do it through XML, maybe I could prescale the graphics. In this case, how should I prescale them?


This is a bit of a hack, but it would allow you to do this in xml.

If you know that, for example, the top image is X% of the size of the bottom one, then you can use LinearLayout's layout_weight to position and size the top image in terms of percentage of the screen:

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView android:id="@+id/left_filler" android:layout_weight="20"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <ImageView android:id="@+id/top_image" android:layout_weight="50"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <ImageView android:id="@+id/right_filler" android:layout_weight="30"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>
 ... bottom image

The above would size top_image at 50% of the screen with an offset of 20% from the left. As long as top_image is 50% the size of bottom_image, this will keep similar scale.

Alternatively, the "right" way to do this is probably to override onDraw() in a custom view and use canvas drawing methods.


You could use the Canvas class method drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) for drawing the specified bitmap by scaling/translating automatically to fill the destination rectangle. This can be used for both the bitmaps with different Rect. The Rect can be formulated by dividing the current width and height of the layout. So that the program will scale the images in accordance with devices having different screen size.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜