LoginSignup
39
40

More than 5 years have passed since last update.

UIImageView 画像リソースを使わないお手軽Highlighted

Posted at

UIImageViewは通常時とハイライト時の2種類の画像を設定出来ます。
例えば以下のようなNormalとHighlightedの2種類の画像を用意してコードでhighlightedを切り替えると、UIImageViewの選択状態と非選択状態をわかりやすく表せます。
Normal Highlighted

Sample.m
// それぞれの画像で初期化
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Normal"]
                                             highlightedImage:[UIImage imageNamed:@"Highlighted"]];

// highlightedで画像の切替が出来る
imgView.highlighted = YES;
imgView.highlighted = NO;

けど、わざわざHighlighted用の画像用意するのは・・・めんどくさい。
コードで画像合成するのも・・・めんどくさい。
他のViewを重ねるのも・・・ちょっと煩雑。

というわけでHighlighted用の画像リソース、画像合成、他のViewもなしなお手軽Highlighted実装です。
やり方はUIImageViewのbackgourndColorとalphaをいじるだけです。

サンプルコード

画像をtouchDown時にHighlighted(少し暗く)でtouchUpになったらNormalの状態に戻るサンプルです。
簡単に実装するために前回投稿したtouchDownとtouchUpのイベントをblockで設定出来るジェスチャークラスを使います。
例えば画像をボタンの様にタップしたときなどの、フィードバックをわかりやすくしたいときに使えます。

Sample.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Normal"]];
    // タッチイベントを受け付ける
    self.imageView.userInteractionEnabled = YES;

    YSTapUpDownGestureRecognizer *tap = [[YSTapUpDownGestureRecognizer alloc] initWithTouchDown:^(YSTapUpDownGestureRecognizer *tapGesture, NSSet *touches, UIEvent *event){
         // 少し暗くする
        self.imageView.backgroundColor = [UIColor blackColor];
        self.imageView.alpha = 0.8f;
    }touchUp:^(YSTapUpDownGestureRecognizer *tapGesture, NSSet *touches, UIEvent *event, BOOL isTouchUpInside){
         // 通常に戻す
        self.imageView.backgroundColor = [UIColor clearColor];
        self.imageView.alpha = 1.f;
    }];

    [self.imageView addGestureRecognizer:tap];

透明部分がある画像や色合いをちゃんと調整したい場合はHighlighted用の画像を用意する必要がありますが、touchDown時にちょっと暗くしたいくらいだったらこれで事足りると思います。

参考

もしかしたらよくある手法なのかもしれませんが、すごくはっとするアイデアでした。

39
40
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
40