如何在图片中实现UILabel中的背景图像?

时间:2011-12-27 16:40:45

标签: iphone objective-c ios uiimage uilabel

如何达到以下效果?

我希望当我的UIImage宽度小于UILabel宽度时,我的图片应该只显示一次,如下所示。

我已经使用UILabelUIImage完成了更多工作。请参阅我之前的问题:How to stretch Image to fill the Label Width set in Background in UILabel?

但是现在我希望UILabel ...:D

更有趣

UILabel with small Image than width repeats only once...

编辑:

SBLabel *lbl = [[SBLabel alloc] initWithFrame:CGRectMake(0, 50, 320, 28)];
lbl.text = @"Hello World!!!...";
UIImage *img = [UIImage imageNamed:@"cn3.png"];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 50, 320, 28)];
imgView.image = img;
[lbl setNonRepeatingBackgroundImage:imgView];
[self.view addSubview:lbl];

[imgView release];

3 个答案:

答案 0 :(得分:0)

if (image.size.width < label.size.width ||image.size.height < label.size.height )
{
//rect here is frame of image
   [img drawInRect:rect];
   label.backgroudColor = [UIColor clearColor];
}

答案 1 :(得分:0)

似乎最直接的解决方案是让您的UIImage坐在UILabel后面,而您的UILabel具有透明的背景色。

修改

假设您正在使用ARC ......

<强> SBLabel.h

#import <UIKit/UIKit.h>

@interface SBLabel : UILabel

@property (nonatomic, strong) UIImageView *nonRepeatingBackgroundImage;

@end

<强> SBLabel.m

#import "SBLabel.h"

@implementation SBLabel

@synthesize nonRepeatingBackgroundImage;

- (void)setNonRepeatingBackgroundImage:(UIImageView *)aNonRepeatingBackgroundImage {
    nonRepeatingBackgroundImage = aNonRepeatingBackgroundImage;
    [self addSubview:aNonRepeatingBackgroundImage];
    [self sendSubviewToBack:aNonRepeatingBackgroundImage];
    [self setBackgroundColor:[UIColor clearColor]];
}

@end

将UILabel添加到父视图后,需要调用此setter方法。我没有测试,但我相信它应该工作,可能需要一些调整,但希望它解释如何Subillass UILabel进行自定义增强,如此。

答案 2 :(得分:0)

UILabel的子类看起来像这样(没有ARC)

CustomLabel.h

#import <UIKit/UIKit.h>

@interface CustomLabel : UILabel {
    UIImage *mImage;
}
@property (retain) UIImage *image;
@end

CustomLabel.m

#import "CustomLabel.h"

@implementation CustomLabel

- (void)dealloc {
    self.image = nil;
    [super dealloc];
}

- (void)drawRect:(CGRect)rect {
    [mImage drawAtPoint:CGPointMake(0, 0)];
    [super drawRect:rect];
}

- (UIImage*)image {
    return mImage;
}

- (void)setImage:(UIImage *)image {
    self.backgroundColor = [UIColor clearColor];

    if(mImage)
        [mImage release];
    mImage = [image retain];
    [self setNeedsDisplay];
}
@end

用法

yourCustomLabel.image = [UIImage imageNamed:@"test.png"];