如何达到以下效果?
我希望当我的UIImage
宽度小于UILabel
宽度时,我的图片应该只显示一次,如下所示。
我已经使用UILabel
和UIImage
完成了更多工作。请参阅我之前的问题:How to stretch Image to fill the Label Width set in Background in UILabel?。
但是现在我希望UILabel
...:D
编辑:
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];
答案 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"];