How do I prevent a button's background image from stretching?

后端 未结 10 2012
执笔经年
执笔经年 2021-01-30 16:22

I\'m allocating a UIButtonTypeCustom UIButton to a UIView with a background image that is smaller than the button\'s frame. Reason why the image is smaller is because I\'m tryin

10条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-30 16:49

    Answerbot answers the question with what is proper and correct to do. Don't fight the OS and use things as intended is always good advice. However, sometimes you need to break the rules.

    I was able to mask the enlarged background image (not prevent it) by overlaying it with a black CAlayer then overlaying again with a properly resized image CAlayer. This was all done by creating a subclass of UIButton and overwriting the setHighlighted method.

    NEED CODE?

    - (void)setHighlighted:(BOOL)highlighted
    {
    super.highlighted = highlighted;
    
    //
    //Whenever an image needs to be highlighted, create a dimmed new image that is correctly       sized. Below it is a englarged stretched image.
    //
    if (highlighted != _previousHighlightedSate)
    {
        _previousHighlightedSate = highlighted;
    
        if (highlighted)
        {
            //Create a black layer so image can dim
            _blackLayer = [CALayer layer];
            _blackLayer.bounds = self.bounds;
            CGRect rect = _blackLayer.bounds;
            rect.size.width = rect.size.width*2;
            rect.size.height = rect.size.height*2;
            _blackLayer.bounds = rect;
            _blackLayer.backgroundColor = [[UIColor blackColor] CGColor];
    
            //create image layer
            _nonStretchImageLayer = [CALayer layer];
            _nonStretchImageLayer.backgroundColor = [UIColor blackColor].CGColor;
            _nonStretchImageLayer.bounds = CGRectMake(0  , 0, self.bounds.size.width, self.bounds.size.height);
            _nonStretchImageLayer.frame = CGRectMake(0  , 0, self.bounds.size.width, self.bounds.size.height);
            _nonStretchImageLayer.contentsGravity = kCAGravityResizeAspect;//default is to resize
            _nonStretchImageLayer.contents = (id)self.imageView.image.CGImage;
            _nonStretchImageLayer.opacity = 0.5;
    
            //add layers to image view
            [self.imageView.layer addSublayer:_blackLayer];
            [self.imageView.layer addSublayer:_nonStretchImageLayer];
        }
        else
        {
            //remove from image view
            [_blackLayer removeFromSuperlayer];
            [_nonStretchImageLayer removeFromSuperlayer];
    
            //nil them out.
            _blackLayer = nil;
            _nonStretchImageLayer = nil;
        }
    }  
    

    Inspiration for this work around came from here

提交回复
热议问题