37

如何设置背景图像UITextView

4

10 回答 10

72

您可以拥有一个UIImageView包含背景图像和同级的UITextView兄弟,然后在 Interface Builder 中移动文本视图以与图像视图重叠(或者如果以编程方式将它们都添加到同一个父视图中)。您还需要确保文本视图不是不透明的,并给它一个0% 的不透明度背景

于 2009-04-17T09:46:02.470 回答
45
UITextView *textView = [[UITextView alloc]initWithFrame: window.frame];
textView.text = @"text\n text\n text";
UIImageView *imgView = [[UIImageView alloc]initWithFrame: textView.frame];
imgView.image = [UIImage imageNamed: @"myImage.jpg"];
[textView addSubview: imgView];
[textView sendSubviewToBack: imgView];
[window addSubview: textView];
于 2009-04-17T11:23:43.127 回答
42

@durai:您的图像有高度限制,如果在向下滚动后出现空白背景,则会出现白色背景,然后您可以重复相同的图像。

这可能会有所帮助:

textView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed: @"Image.png"]];
于 2011-01-20T13:14:16.067 回答
11

只是一个澄清,当尝试来自@oxigen的答案#9 时,我发现这一行:

UIImageView *imgView = [[UIImageView alloc]initWithFrame: textView.frame];

是相对的textView.frame。因此,如果您希望它完全重叠,则您的xy值需要为 0,0,这意味着您想要类似的东西:

UIImageView *imgView = [[UIImageView alloc]initWithFrame:textView.bounds];
于 2010-11-11T09:53:48.327 回答
6

我找到了一种简单的方法来设置背景图像。

h 文件

@interface FNTextView : UITextView

@end

文件

...
- (void)drawRect:(CGRect)rect
{
    [self.bgImage drawInRect:rect];

    [super drawRect:rect];
}

- (void)initHandler
{
    self.bgImage = [[UIImage imageNamed:@"textview_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 4, 4, 4)];
}
...
于 2012-12-14T16:21:47.353 回答
5
[txtView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"image.png"]]];
于 2013-09-18T08:57:46.860 回答
2

对于平铺背景,我喜欢这个解决方案

UIImage *patternImage = [UIImage imageNamed:@"image.png"];
UIColor* color = [UIColor colorWithPatternImage:patternImage];
textView.backgroundColor = color;
于 2012-03-12T13:24:15.203 回答
1

不确定,但您可以尝试以下操作,假设您的背景图像由 UIImageView 处理:

[myTextView addSubview: myImageView];

请注意,您可能需要更改 UITextView 的 alpha/opaque 属性的值。

亲切的问候。

于 2009-04-17T09:35:58.640 回答
1
UITextView *textView=[[UITextView alloc]initWithFrame: CGRectMake(20, 20, 40, 40)];
textView.text = @"this is a test \n this is test \n this is a test";
UIImageView *img = [[UIImageView alloc]initWithFrame: textView.frame];
img.image = [UIImage imageNamed: @"image.png"];
[self.view addSubview:textView];
[self.view insertSubview:img belowSubview:textView];
于 2012-12-05T10:51:25.767 回答
1

@dulcanwilcox 和 @oxigen 的答案都有效,但是,如果图像被用来显示某种边框,另外可以调整背景图像的大小。

UITextView *textView = [[UITextView alloc]initWithFrame: window.frame];
textView.text = @"Some text...";

UIImageView *imgView = [[UIImageView alloc]initWithFrame: textView.frame];
imgView.image = [[UIImage imageNamed: @"image"] resizableImageWithCapInsets:UIEdgeInsetsMake(8, 8, 8, 8)];

[textView addSubview:imgView];
[textView sendSubviewToBack:imgView];

[window addSubview:textView];

查看resizableImageWithCapInsets:(UIEdgeInsets)capInsets的文档。

于 2013-03-20T16:56:59.247 回答