【发布时间】:2016-12-09 06:39:21
【问题描述】:
我需要实现个人资料 imageView 以与一定数量的成员聊天。
它应该看起来像这样:
因此,根据成员的数量,imageview 应该被分成适当的部分,这些部分应该由每个聊天成员的适当照片组成。
upd:我找到了一些解决方案(见下文)并且它有效,但是有些图像被拉伸了,因为它们的实际比例是 1:1。
如何按比例拉伸UIImage(比例为 1:1)以适合矩形大小?
class ProfileImageHelper {
class func collageImage (rect:CGRect, images:[UIImage]) -> UIImage {
let maxImagesPerRow = 2
let maxSide = rect.width / CGFloat(maxImagesPerRow)
var index = 0
var currentRow = 1
var xtransform:CGFloat = 0.0
let transformOffset:CGFloat = 1.5
var ytransform:CGFloat = 0.0
var smallRect:CGRect = CGRect.zero
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)//UIScreen.main.scale)
for img in images {
index += 1
let x = index % maxImagesPerRow //row should change when modulus is 0
//row changes when modulus of counter returns zero @ maxImagesPerRow
if x == 0 {
//last column of current row
//xtransform += CGFloat(maxSide)
smallRect = CGRect(x: xtransform, y: ytransform, width: maxSide - transformOffset, height: (rect.size.height / CGFloat(currentRow)) - transformOffset)
//reset for new row
currentRow += 1
xtransform = 0.0
ytransform = (maxSide * CGFloat(currentRow - 1)) + transformOffset
} else {
//not a new row
if xtransform == 0 {
//this is first column
//draw rect at 0,ytransform
smallRect = CGRect(x: xtransform, y: ytransform, width: maxSide - transformOffset, height: (rect.size.height / CGFloat(currentRow)) - transformOffset)
xtransform += CGFloat(maxSide) + transformOffset
} else {
//not the first column so translate x, ytransform to be reset for new rows only
smallRect = CGRect(x: xtransform, y: ytransform, width: maxSide - transformOffset, height: (rect.size.height / CGFloat(currentRow)) - transformOffset)
xtransform += CGFloat(maxSide) + transformOffset
}
}
//draw in rect
img.draw(in: smallRect)
}
let outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage!
}
}
有什么建议吗?
【问题讨论】:
-
在 coregraphics 上绘制图像并作为 uiimage 返回。
-
最好的方法是使用 3 个图像视图并在该图像视图中使用 breazerpath UIBezierPath 绘制 3 个不同图像的cornerradius
-
一个 UIImageView 就足够了。为什么要为这么简单的组件浪费3个ImageView的资源??
-
上图只是示例。我需要将任意数量的图像放在一个图像中,具体取决于聊天成员的数量。
-
子类 uiimageview 以接受 uiimage 数组,使用数组的 .count 来决定图像的切片数,使用 GeneCode 建议的 coregraphics 将最终图像拼凑成图像视图
标签: ios objective-c swift uiimageview user-profile