31

したがって、アプリには200x200のサイズのサムネイルのコレクションがあります。元の画像にはこの比率がない場合があるため、この画像を正方形にトリミングする予定です。

現在、サムネイルに収まるように画像をストレッチするだけなので、元の画像サイズが400x800であるとすると、画像は非常に押しつぶされたように見えます。この画像をトリミングして、幅/高さが最短になるようにしてから正方形にトリミングしたかったので、上記の例では400x400にトリミングされます。

CSS を介してこれを簡単に行う方法はありますか、またはこれを行うためにある種の JS を使用する必要がありますか?

4

3 に答える 3

1

私は独自の解決策を思いついたので、他の誰かがこのスレッドを見つけた場合に備えて、ここで共有すると思いました. background-size: cover ソリューションが最も簡単ですが、IE7 でも機能するものが必要でした。jQuery と CSS を使用して思いついたものを次に示します。

注: 私の画像は「プロフィール」画像であり、正方形に切り取る必要がありました。したがって、いくつかの関数名。

jQuery:

cropProfileImage = function(pic){
    var h = $(pic).height(),
        w = $(pic).width();

    if($(pic).parent('.profile-image-wrap').length === 0){
                     // wrap the image in a "cropping" div
         $(pic).wrap('<div class="profile-image-wrap"></div>');
    }

      if(h > w ){
          // pic is portrait
          $(pic).addClass('portrait');
          var m = -(((h/w) * 100)-100)/2; //math the negative margin
          $(pic).css('margin-top', m + '%');    
      }else if(w > h){ 
          // pic is landscape
          $(pic).addClass('landscape'); 
          var m = -(((w/h) * 100)-100)/2;  //math the negative margin
          $(pic).css('margin-left', m + '%');
      }else {
        // pic is square
        $(pic).addClass('square');
      }
 }

// Call the function for the images you want to crop
cropProfileImage('img.profile-image');

CSS

.profile-image { visibility: hidden; } /* prevent a flash of giant image before the image is wrapped by jQuery */

.profile-image-wrap { 
      /* whatever the dimensions you want the "cropped" image to be */
      height: 8em;
      width: 8em;
      overflow: hidden; 
 }

.profile-image-wrap img.square {
      visibility: visible;
      width: 100%;  
 }

 .profile-image-wrap img.portrait {
      visibility: visible;
      width: 100%;
      height: auto;
 }

 .profile-image-wrap img.landscape {
      visibility: visible;
      height: 100%;
      width: auto;
 }
于 2014-02-28T21:59:00.323 に答える