简体   繁体   English

IOS / Objective-C:在自定义单元中制作圆形图像的代码

[英]IOS/Objective-C: Code to Make Round Image in Custom Cell

The following code is working fine to make a square image round when placed in cellForRowAtIndexPath. 将以下代码放置在cellForRowAtIndexPath中时,可以很好地使正方形图像变圆。

However, when I move the code to a custom cell, every time the tableview changes, it spreads the circle all the way across the table row into a horizontal blur. 但是,当我将代码移动到自定义单元格时,每次tableview更改时,它都会将圆一直扩展到整个表行,成为水平模糊。

在此处输入图片说明

 //following crops and rounds image

    CGSize itemSize = CGSizeMake(40, 40);
    UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
    CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);

    [self.iconView.image drawInRect:imageRect];
    self.iconView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.iconView.layer.masksToBounds=YES;
    self.iconView.layer.cornerRadius=20.0;
    self.iconView.frame = CGRectMake(20, 20, 500, 50);

    //   [cell.iconView.image drawInRect:imageRect];
    //   cell.iconView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

In custom cell, I have been placing this code after the following: 在自定义单元格中,我将以下代码放置在以下位置:

self.iconview.image = [UIImage imageNamed:@"test.jpg"];

Does anyone know how I might fix this and still use a custom cell? 有谁知道我该如何解决此问题并仍然使用自定义单元格? Thanks in advance for any suggestions. 在此先感谢您的任何建议。

The issue is what "when I move the code to a custom cell" means - which you do not explain. 问题是“当我将代码移至自定义单元格时”的含义-您无需解释。 But the problem is that iconView itself is being resized - it is being made wider. 但是问题在于iconView本身正在调整大小-它正在变宽。 If you don't want that to happen, give it different constraints so that that doesn't happen. 如果您不希望发生这种情况,请给它不同的约束,以免发生这种情况。

There is no need for you to start the image context and get all the way down into CoreGraphics. 您无需启动图像上下文并完全进入CoreGraphics。

I accomplish this by: 我通过以下方式完成此任务:

imageView.image = myUIImage
imageView.layer.cornerRadius = imageView.bounds.size.width / 2

There is simple way to make rounded image in custom cell: 有一种简单的方法可以在自定义单元格中制作圆形图像:

imageView.layer.cornerRadius = imageDemo.frame.size.width / 2;

imageView.clipsToBounds = YES;

or follow this link 或点击此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM