[英]How to centre the background image in a UIView without streching it
我想在UIView
居中背景圖像。 背景圖像小於UIView
本身,並且我不想拉伸它,即我希望它具有其原始大小。 我寫了下面的代碼
UIImage *backgroundImage=[[UIImage alloc] initWithContentsOfFile:@"analog_display_bgr.png"];
CGSize backgroundImageSize= CGSizeMake (backgroundImage.size.width,backgroundImage.size.height);
UIGraphicsBeginImageContext(backgroundImageSize);//self.frame.size
CGRect backgroundImagePosition = CGRectMake(self.bounds.origin.x+m_center.x-backgroundImage.size.width/2.0, self.bounds.origin.y+m_center.y-backgroundImage.size.height/2.0, backgroundImage.size.width, backgroundImage.size.height);
[[UIImage imageNamed:@"analog_display_bgr.png"] drawInRect:backgroundImagePosition];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.backgroundColor = [[UIColor alloc] initWithPatternImage:image];
我應該做這份工作,但是不起作用。
知道有什么問題嗎? 提前致謝。
我仍然無法復制您正在談論的拉伸效果,但是我相信您的大部分問題都在這一行中UIGraphicsBeginImageContext(backgroundImageSize);
。 您想要的是使新圖像成為視圖的大小,而不是現有的大小。 無論如何,這段代碼對我有用。 讓我知道它是否也適用於您。
UIImage *backgroundImage = [UIImage imageNamed:@"analog_display_bgr.png"];
UIGraphicsBeginImageContext(self.bounds.size);
CGRect imagePosition = CGRectMake((self.bounds.size.width / 2) - (backgroundImage.size.width / 2),
(self.bounds.size.height / 2) - (backgroundImage.size.height / 2),
backgroundImage.size.width,
backgroundImage.size.height);
[backgroundImage drawInRect:imagePosition];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.backgroundColor = [[UIColor alloc] initWithPatternImage:image];
我嘗試了您的代碼,卻一無所獲。 完全空白的視圖。 我將按照您的描述進行操作的方式如下:
UIImage *backgroundImage = [UIImage imageNamed:@"analog_display_bgr.png"];
UIImageView *imageView = [[UIImageView alloc]initWithImage:backgroundImage];
CGRect imageViewFrame = imageView.frame;
imageViewFrame.origin.x = (self.bounds.size.width / 2) - (imageView.bounds.size.width / 2);
imageViewFrame.origin.y = (self.bounds.size.height / 2) - (imageView.bounds.size.height / 2);
[imageView setFrame:imageViewFrame];
[self addSubview:imageView];
我在UIView子類的- (void)awakeFromNib
中進行了嘗試,並且工作正常。 在視圖中心繪制圖像而不拉伸它。
如果我對您的理解正確,那么您希望圖像成為視圖的背景,那么在其他所有內容之后。 假設您將UIImageView添加到所有其他視圖的后面,我上面提供的代碼將做到這一點。 如果您仍然希望將圖像繪制為backgroundColor,就像我知道的那樣,我會看看是否可以使它工作。
很抱歉發布了另一個答案,但是我無法在評論中添加圖片,因此我想確保自己完全了解您想要的內容。
因此,據我了解,這就是您的代碼所要做的
這是我的代碼的作用:
但是您想要的是更多這樣的東西:
那是對的嗎? 如果是,是哪一個? 一個在左邊還是右邊?
您可以將UIImageView
添加到您的UIView
並為其設置圖像。 您也可以使用UIViewContentMode
屬性,可能clipToBounds = YES
具有clipToBounds = YES
UIViewContentModeCenter
或UIViewContentModeScaleAspectFill
:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.