如何直接在UIView上设置图像?

18

有没有人能告诉我如何直接在UIView上设置图片?这是我的代码:

 UIView *view=[[UIView alloc]init];
 [view setImage:[UIImage imageNamed:@"image.png"]];

你不想使用UIImageView吗? - Maulik
你需要使用UIImageView。 - Vincent Bacalso
2
你可以将其设置为背景 aView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"yourimage.png"]]; - Kamleshwar
6个回答

21
UIView *view=[[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
[view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"a.png"]]];
希望这能帮到你。

11

这很简单。尝试:

UIView * view = [[UIView alloc] initWithFrame:CGRectMake(origin_x, origin_y, width, height)]; 
UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"a.png"]];
[view addSubview:imageView];
[imageView release];
你还可以操作 UIImageViewframe 属性,将其在 UIView 中移动。希望这有所帮助!

4
   UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
        [imageView setImage:[UIImage imageNamed:@"320_480clouds_background.png"]];
        self.tableView.backgroundView = imageView;
        [imageView release];

希望这能帮到你。

4

Swift版本:

let view = UIView(frame: CGRectMake(0, 0, 640, 200))
view.backgroundColor = UIColor(patternImage: UIImage(named: "myImage")!)

Swift 3:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 640, height: 200))
view.backgroundColor = UIColor(patternImage: UIImage(named: "myImage")!)

2
你可以尝试这个方法:
UIView *aView=[[UIView alloc]init];

UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"anImage.png"]];
aView.backgroundColor = background;
[background release];

但是为了良好的编程习惯,您应该使用UIImageView来显示图像。 - Maulik

2

我在这里将CGImage分配给图层的contents属性,该属性接受CGImage或NSImage。您只能将CGImage或NSImage分配到contents属性。

layerView.layer.contents = UIImage(named: "Mario.png")?.cgImage

请提供一些关于您的代码如何解决 OP 的问题以及为什么它比已有答案更好的解释。这可能会有所帮助 - [回答] - Tom
1
我不会说这是更好的每个人的答案,但这只是另一种你可以做到的方式。 - Anirudha Mahale
尽管如此,解释其不同之处仍是必要的。 - Tom
将 CGImage 分配给图层的 contents 属性,该属性接受 CGImage 或 NSImage。您只能将 CGImage 或 NSImage 分配给 contents 属性。 - Anirudha Mahale
我使用CALayer对象在layerView上完成了这个操作,而layerView是UIKit的低级对象。 - Anirudha Mahale

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接