HomepageLog inSign upSite MapPasser en français  
Search
Sdl's Egosystem
s t e p h a n e d e l u c a . c o m


مصطفی الجوّال

Lite Edition, Year 2017
Vol. 24, Wed. Jun. 28th, 2017 14:13
M C M L X X X I I :   T H I R T Y - F I V E   Y E A R S   O F   P R O G R A M M I N G   A N D   T E C H N O L O G Y   D E S I G N 
BLOG
Home
Curriculum Vitæ
Résumé
Blog
IPHONE® & IPAD® DEVELOPMENT
LeKiosque™: First 3D Newsstand For IPad®
MaryChard™: Hiperf 3D & Collada
SdlImage™: 3D Graphics Booster
MOBILE/TELCOS
Mobile Web: 35M Pages/month
Mobile Earth
Mobile MMO
Wireless Multiplayer
VIDEO GAMES INDUSTRY
Nightmare Creatures 3 (Ubisoft)
Nightmare Creatures 2 (Konami)
Commando (Namco)
Angel Quest (GT Interactive)
Storm (Electronic Arts)
Asterix & Books (Canal Plus)
CONSULTING
Consulting & M&A
Business
3D NEWSSTAND
SINCE 2010
MOBILE WEB
2009
CONSULTING M&A
2007
MOBILE EARTH
2006
MOBILE MMO
2005
WIRELESS MULTIPLAYER
2004
VIDEO GAMES INDUSTRY
1994-2003
BEFORE
<1994

iOS: compute the aspect fit rectangle of an image within a given rectangular container

May 18th, 2013 22:18 by sdelucaPermalink | TrackBack: http://stephanedeluca.com/trackback/892 — exists for 4 years & a month ago

I seldom give code snippet. But it must be recognized that simple geometrical operations are not really understood by most of programmers. As a consequence, they often come up with long and complex source code which is even not solid, bugs being around.

The objective is to compute the bounding rectangle of an image which is placed in a given rectangular container, so that the image is stretched to fit into it, keeping the original image aspect ratio.

In addition, the code center the image within the bounding view.

The first step is to compute the two possible scale factor. As we're looking for the maximum constraint, we pick the smaller scale factor to decide what direction to keep. Then we recompute the second direction by combining the two scale factors.

The resulting code is short, as follows:

- (CGRect) getAspectFitRectangle:(UIImageView *)iv
                           image:(UIImage *)im {
    // view to embed the image
    float vw = iv.frame.size.width;
    float vh = iv.frame.size.height;

    // image to be embeded in the view
    float w = im.size.width;
    float h = im.size.height;

    // compute
    float scaleW = vw/w;
    float scaleH = vh/h;

    if (scaleW>scaleH) {
        // keep height, recompute width
        float iw = vw/scaleW*scaleH;
        // compute horizontal translation
        // to center the image
        float x = (vw-iw)*.5f;
        return CGRectMake(x,0, iw,vh);
    }
    else {
        // keep width, recompute height
        float ih = vh/scaleH*scaleW;
        // compute vertical translation
        // to center the image
        float y = (vh-ih)*.5f;
        return CGRectMake(0,y, vw,ih);
    }
}




Copyright © 1994 ˜ 2017 dsei.biz / Stéphane de Luca — All Rights Reserved | 02:13 PM RSS RSS Feed  | Best viewed with Apple logo Safari