美文网首页
UIButton按钮的图片按比例缩放

UIButton按钮的图片按比例缩放

作者: 一抹相思泪成雨 | 来源:发表于2020-11-09 17:48 被阅读0次
    视觉给的图片比较大,但是,用在按钮上显示过大怎么办?

    1.设置按钮的imageEdgeInsets,比如设置上下间距,从而设置图片的高度。

    UIEdgeInsets UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) {
        UIEdgeInsets insets = {top, left, bottom, right};
        return insets;
    }
    

    2.设置按钮图片的拉伸属性UIViewContentMode;中的UIViewContentModeScaleAspectFit,按最小边填充

    typedef NS_ENUM(NSInteger, UIViewContentMode) {
        UIViewContentModeScaleToFill,
        UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
        UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    };
    

    3.代码设置

        UIButton *kfButton = [UIButton buttonWithType:UIButtonTypeCustom];
        kfButton.frame = CGRectMake((self.view.bounds.size.width-136)*0.5, 200, 136, 40);
        kfButton.imageEdgeInsets = UIEdgeInsetsMake(13, -10, 13, 0);
        kfButton.titleEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
        [kfButton setTitle:@"xxx在线客服" forState:UIControlStateNormal];
        [kfButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [kfButton setImage:[UIImage imageNamed:@"search_search_service"] forState:UIControlStateNormal];
        kfButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
        kfButton.layer.cornerRadius = 3;
        kfButton.layer.borderWidth = 1;
        kfButton.layer.masksToBounds = YES;
        kfButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [kfButton addTarget:self action:@selector(kfButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:kfButton];
    
    

    4.效果展示


    image.png

    相关文章

      网友评论

          本文标题:UIButton按钮的图片按比例缩放

          本文链接:https://www.haomeiwen.com/subject/twqrbktx.html