[英]Resizing image to fit UIImageView
我對目標c還是很陌生,但我的目標才剛剛開始。 我想做一些非常簡單的事情,但是事實證明這是一個很大的挑戰:
我正在嘗試將圖像顯示到UIImageView
。 我顯示的圖像很大,我希望將其縮小以適合UIImageView
。 我嘗試設置AspectFit
View模式,但是圖像顯示為原始大小,並被UIImageView
裁剪。 我的代碼如下:
- (void)changeImages
{
UIImage* img11 = nil;
img11 = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"dog" ofType:@"jpeg"]];
u11.contentMode = UIViewContentModeScaleAspectFit;
u11.image = img11;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self changeImages];
}
誰能對此有所啟發?
謝謝!
嗨,我會嘗試這個...
- (void)changeImages
{
UIImage *img11 = [UIImage imageNamed@"dog.jpeg"];
u11.contentMode = UIViewContentModeScaleAspectFit;
u11.clipsToBounds = YES;
[u11 setImage:img11];
}
- (void)viewWillAppear:animated
{
[super viewWillAppear:animated];
[self changeImages];
}
這將縮放圖像(向上或向下),使其適合imageView內。 不需要clipsToBounds,但可以阻止圖像顯示在imageView框架之外。
HTH。
添加到您的UIViewController.m:
-(UIImage *)resizeImage:(UIImage *)image imageSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0,0,size.width,size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// here is the scaled image which has been changed to the size specified
UIGraphicsEndImageContext();
return newImage;
}
使用方法:
UIImage *image = [UIImage imageNamed:@"image.png"];
CGSize size = CGSizeMake(50, 63); // set the width and height
UIImage *resizedImage = [self resizeImage:image imageSize:size];
希望對您有所幫助。
CGSize size=CGSizeMake(79, 84);//set the width and height
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0,0,size.width,size.height)];
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
//here is the scaled image which has been changed to the size specified
UIGraphicsEndImageContext();
這可以肯定地工作,並且不要忘記導入QuartzCore FrameWork。
祝您編碼愉快(^ _ ^)....
您還可以在Interface Builder中的“屬性”檢查器中將View:Mode設置為Aspect Fit。
我做了以下工作,它幫助將模式從默認值“縮放為填充”更改為“縱橫比填充”
並添加一行代碼,如下所示(我在單元格配置中做到了):
cell.photo.clipsToBounds = true
我知道這很老了,但我想根據Stanford 193p 2017講座11(約18:45)和所有想迅速搜尋的人添加一個回復,因為這是第一個顯示給我的搜索結果。
基本上,繼承UIView並使它看起來像:
class U11: UIView {
var myImage: UIImage? { didSet { setNeedsDisplay() }}
override func draw(_ rect: CGRect) {
myImage?.draw(in: bounds)
}
}
然后使用以下方法設置圖像:
func changeImage() {
if let img11 = UIImage(named: "dog.jpeg"){
u11.myImage = img11
}
}
這非常簡單,圖像占據了視圖邊界內的整個空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.