我只想以编程方式创建一个UIImageView,在点(50,50)处显示一个20by20点。(点的图像称为draw.png)。出于某种原因,屏幕上没有显示任何内容。
继承我的代码:
- (void)viewDidLoad
{
UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)];
dot.image=[UIImage imageNamed:@"draw.png"];
[self.view addSubview:dot];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
}
答案 0 :(得分:37)
首先,确保你的项目中存在draw.png并且你正在引用它(所以如果它是draw.PNG你应该放@"draw.PNG"
)。此外,请在所有内容之前致电[super viewDidLoad]
。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)];
dot.image=[UIImage imageNamed:@"draw.png"];
[self.view addSubview:dot];
}
答案 1 :(得分:7)
试试这个: -
UIImageView *imageview = [[UIImageView alloc]
initWithFrame:CGRectMake(50, 50, 20, 20)];
[imageview setImage:[UIImage imageNamed:@"AppleUSA1.jpg"]];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imageview];
答案 2 :(得分:2)
此代码是正确的。确保项目中存在draw.png
。您可以通过检查[UIImage imageNamed:@"draw.png"]
是否未返回nil
来执行此操作。
另外,请确保图像视图顶部没有其他视图。
答案 3 :(得分:2)
确保图片在您的项目中..
UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 50, 50)];
[imgView setImage:[UIImage imageNamed:@"xyz.jpg"]];//if your images extension is .png than no need to write extension of an image..
[self.view addSubview:imgView];
答案 4 :(得分:2)
在斯威夫特:
let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 20, height: 20))
imageView.image = UIImage(named: "draw.png")
self.view.addSubview(imageView)
答案 5 :(得分:1)
此代码与UIImageView完美匹配:
UIImageView *IMG_view= [[UIImageView alloc] initWithFrame:CGRectMake(20 ,50 ,40 ,40)];
[IMG_view setTag:100]; //[IMG_view setTag:indexPath.row];
IMG_view.layer.borderWidth= 0.5 ;
IMG_view.layer.borderColor= [[UIColor clearColor] CGColor];
IMG_view.layer.cornerRadius= 3;
IMG_view.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:IMG_view];
IMG_view.image=[UIImage imageNamed:@"Loading_50x50.png"];