【问题标题】:How to set a background image to label如何将背景图像设置为标签
【发布时间】:2010-08-04 21:39:36
【问题描述】:

我想在按钮图像上显示一个数字,例如大小为 30*28 的徽章,

我在按钮图像的顶部设置了一个徽章图像.. 在徽章图像之上,我应该能够显示文本或数字,并且我的徽章尺寸为 30*28。

所以,为了实现这一点,我想在我的按钮图像顶部设置一个标签,因此我想将标签背景设置为一些称为徽章图像的图像。

【问题讨论】:

    标签: ios uilabel


    【解决方案1】:

    在堆栈溢出本身中发现了这一点,因为上面的代码只是给出了没有标签的背景

    对我有用 所以分享

    theLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blah"]];
    

    见:Adding Background image to UILabel

    【讨论】:

      【解决方案2】:

      您不能将背景图像添加到 UILabel,但您可以将 UIImageView 作为子视图添加到 UILabel。确保 UILabel 具有 backgroundColor = [UIColor clearColor]; 以提高透明度。

      例如

      UIImageView *labelBackground = [[UIImageView alloc] 
          initWithImage:[UIImage imageNamed:@"mybg.png"]];
      [myLabel addSubview:labelBackground];
      [labelBackground release];
      myLabel.backgroundColor = [UIColor clearColor];
      

      应该可以。未经测试。

      【讨论】:

      • 但是没有看到标签文字。只有图片出现了。
      • 错误答案,背景图片可添加到 uilabels !不鼓励将 UIImage 添加为子视图以提供“背景”效果。
      • 请随意使用“过时的答案”一词,因为答案在 2 年前发布时是正确的。 ;) 也就是说,如果人们想要向后兼容旧版 iOS:他们可能仍然会发现这个答案很有用。
      • 此代码将起作用.. 只需记住将子视图发送回。 [myLabel sendSubviewToBack:labelBackground];
      【解决方案3】:

      要使图像适合您的 UIview试试这个代码

      UIImage *backgroundImage = [UIImage imageNamed:@"imageNameHere"];
      
      UIGraphicsBeginImageContext(self.labelName.frame.size);
      [backgroundImage drawInRect:CGRectMake(0, 0, self.labelName.frame.size.width, self.labelName.frame.size.height)];
      UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      
      self.labelName.backgroundColor = [UIColor colorWithPatternImage:newImage];
      

      【讨论】:

        猜你喜欢
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        • 2017-04-12
        • 2020-12-30
        • 2013-07-03
        • 2014-06-23
        • 1970-01-01
        • 2018-04-08
        相关资源
        最近更新 更多