[英]Pasteboard UIImage not using scale
我正在構建自定義鍵盤,無法將圖像添加到粘貼板,並在粘貼的圖像中保持適當的比例和分辨率。 讓我從鍵盤截圖開始說明我的麻煩:
因此,鍵盤左上方的臉部圖片只是一個UIButton,原始圖片設置為背景。 按下按鈕時,圖像將使用以下功能調整大小:
func imageResize(image:UIImage, size:CGSize)-> UIImage {
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(size, false, scale)
var context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
image.drawInRect(CGRect(origin: CGPointZero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
此函數使用適當的比例創建與UIButton相同大小的UIImage,以反映設備的屏幕分辨率。 為了驗證該功能是否正確,我添加了一個UIImageView,其中填充了縮放后的圖像。 縮放后的圖像是看起來放在鍵盤中心附近的圖像。 我使用以下功能添加了UIImageView:
func addImageToBottomRight(image: UIImage) {
var tempImgView = UIImageView(image: image)
self.view.addSubview(tempImgView)
tempImgView.frame.offset(dx: 100.0, dy: 50.0)
}
我嘗試了幾種不同的方法將圖像添加到粘貼板,但是似乎都忽略了圖像的比例,並且顯示的圖像是高分辨率顯示的兩倍:
let pb = UIPasteboard.generalPasteboard()!
var pngType = UIPasteboardTypeListImage[0] as! String
var jpegType = UIPasteboardTypeListImage[2] as! String
pb.image = image
pb.setData(UIImagePNGRepresentation(image), forPasteboardType: pngType)
pb.setData(UIImageJPEGRepresentation(image, 1.0), forPasteboardType: jpegType)
這三種方法均無法正常工作,並且產生的效果與屏幕截圖所示相同。 有人對其他方法有什么建議嗎? 為了進一步闡明我的目標,我希望消息文本框中的圖像在大小和分辨率方面看起來都與鍵盤中的兩個UIImage相同。
以下是UIImage的一些屬性,如果有人好奇,請調整大小:
Starting Image Size is (750.0, 750.0)
Size to scale to is: (78.0, 78.0))
Initial Scale: 1.0
Resized Image Size is (78.0, 78.0)
Resized Image Scale: 2.0
我知道這是一篇過時的文章,但我想分享一下我在復制圖片並將其粘貼到消息傳遞應用程序的特定情況下發現的工作。問題是,當您使用iMessages,whatsapp,messenger等應用程序發送圖片時,那么他們顯示圖像的方式就是使其寬高比適合某個特定的水平寬度(對於這個演示,可以說大約260點)。
從下圖可以看到,如果在發送1x分辨率的圖像時發送150x150的圖像,則圖像將被拉伸並顯示在所需的260寬度框中,從而使圖像呈顆粒狀。
但是,如果在圖像的左側和右側都添加寬度為185的空白邊距,則最終將得到尺寸為520x150的圖像。 現在,如果您在發送該尺寸的圖像時遇到麻煩,則必須將其放入260寬度的框中,最終將520x150的圖像塞進260x75的框中,從而以@ 2x的分辨率獲得75x75的圖像。
您可以使用以下代碼向UIImage添加清晰的顏色邊距
extension UIImage {
func addMargin(withInsets inset: UIEdgeInsets) -> UIImage? {
let finalSize = CGSize(width: size.width + inset.left + inset.right, height: size.height + inset.top + inset.bottom)
let finalRect = CGRect(origin: CGPoint(x: 0, y: 0), size: finalSize)
UIGraphicsBeginImageContextWithOptions(finalSize, false, scale)
UIColor.clear.setFill()
UIGraphicsGetCurrentContext()?.fill(finalRect)
let pictureOrigin = CGPoint(x: inset.left, y: inset.top)
let pictureRect = CGRect(origin: pictureOrigin, size: size)
draw(in: pictureRect)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
defer { UIGraphicsEndImageContext() }
return finalImage
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.