突出显示(点击)时如何使UIImageView变暗?

时间:2013-05-12 18:43:09

标签: ios uiviewcontroller uiimageview uigesturerecognizer

我有一个显示图片的UIImageView。当点击并保持时,只要用户将手指放在图像视图上,我就希望它变暗。基本上,我希望它像UIButton一样。

我目前使用UIGestureRecognizer执行此操作:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self
                                         action:@selector(pictureViewTapped)];
    singleTap.numberOfTapsRequired = 1;
    singleTap.numberOfTouchesRequired = 1;
    [self.pictureImageView addGestureRecognizer:singleTap];
    [self.pictureImageView setUserInteractionEnabled:YES];
}

在我的pictureViewTapped中,我有这个(现在):

- (void)pictureViewTapped {
    NSLog(@"Picture view was tapped!");
}

如何使UIImageView变暗?任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:16)

最简单的方法是在QuartzCore框架中使用图层:

添加:在项目设置中投影的QuartzCore.framework 添加到.h文件:#import

为长按创建手势,而不是按照您描述的行为点击:

 self.longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(darkenImage)];
    [self.imageView setUserInteractionEnabled:YES];
    [self.imageView addGestureRecognizer:self.longTap];
手势激活时调用的

方法:

-(void)darkenImage {
    switch (self.longTap.state) {
        case UIGestureRecognizerStateBegan: // object pressed
        case UIGestureRecognizerStateChanged:
            [self.imageView.layer setBackgroundColor:[UIColor blackColor].CGColor];
            [self.imageView.layer setOpacity:0.9];
            break;
        case UIGestureRecognizerStateEnded: // object released
            [self.imageView.layer setOpacity:1.0];
            break;
        default: // unknown tap
            NSLog(@"%i", self.longTap.state);
            break;
    }
}

答案 1 :(得分:1)

在我的情况下,当将ImageView的图层不透明度设置为0.9时,背景将会显示。

我使用的是使用新图层的解决方案。

let coverLayer = CALayer()
coverLayer.frame = imageView.bounds;
coverLayer.backgroundColor = UIColor.blackColor().CGColor
coverLayer.opacity = 0.0
imageView.layer.addSublayer(coverLayer)

// when tapped
coverLayer.opacity = 0.1

答案 2 :(得分:0)

夫特 - 解决方案:

@IBOutlet weak var imageViewExport: UIImageView!
var tapGestureExport = UILongPressGestureRecognizer()

override func viewDidLoad() {
        super.viewDidLoad()

        imageViewExport.userInteractionEnabled = true

        tapGestureExport = UILongPressGestureRecognizer(target: self, action: "tapGestureExportAction:")
        imageViewExport.addGestureRecognizer(tapGestureExport)
    }

    func tapGestureExportAction(sender: UITapGestureRecognizer) {

        switch(tapGestureExport.state) {
        case UIGestureRecognizerState.Began,
                UIGestureRecognizerState.Changed:
            imageViewExport.backgroundColor = UIColor.blackColor()
            imageViewExport.layer.opacity = 0.9

        case UIGestureRecognizerState.Ended:        // released
            imageViewExport.layer.opacity = 1.0

            default: break // unknown tap 
            }
}