You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MTKView渲染坐标异常:少数用户像素大小不一致问题排查

MTKView渲染画布时部分用户出现像素大小不一致的异常问题

我正在开发一款绘图应用,使用MTKView渲染画布。目前遇到一个问题:仅少数用户会出现像素渲染异常(像素大小不一致),多数用户无此情况。

当前配置与现象

  • 每个像素通过2个三角形渲染
  • MTKView的frame尺寸始终为画布尺寸的整数倍(如100x100画布对应100x100、200x200等frame尺寸)
  • 存在一个基于UIImageView的像素标记网格,可见其与像素未对齐
  • 背景棋盘格图案与像素对齐,但与网格不对齐

此前当视图frame非画布尺寸整数倍时,我遇到过完全相同的问题,已通过上述配置修复。

已确认信息与尝试操作

  • 顶点坐标准确,排除顶点数据问题,确认为渲染层面的异常(截图可见部分像素尺寸明显偏大)
  • 尝试将contentScaleFactor改为1、2、3,均无法解决问题

相关代码配置

MTKView配置

clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0)
delegate = renderer
renderer.setup()
isOpaque = false
layer.magnificationFilter = .nearest
layer.minificationFilter = .nearest

渲染器配置

let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = vertexFunction
pipelineDescriptor.fragmentFunction = fragmentFunction
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm

pipelineState = try? device.makeRenderPipelineState(descriptor: pipelineDescriptor)

渲染器绘制方法

commandEncoder.setRenderPipelineState(pipelineState)
commandEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
commandEncoder.setVertexBuffer(colorBuffer, offset: 0, index: 1)
commandEncoder.drawIndexedPrimitives(
  type: .triangle,
  indexCount: indexCount,
  indexType: .uint32,
  indexBuffer: indexBuffer,
  indexBufferOffset: 0
)

commandEncoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()

Metal文件代码

struct VertexOut {
  float4 position [[ position ]];
  half4 color;
};

vertex VertexOut frame_vertex(constant const float2* vertices [[ buffer(0) ]],
                              constant const half4* colors [[ buffer(1) ]],
                              uint v_id [[ vertex_id ]]) {
  VertexOut out;
  out.position = float4(vertices[v_id], 0, 1);
  out.color = colors[v_id / 4];
  return out;
}

fragment half4 frame_fragment(VertexOut v [[ stage_in ]]) {
  half alpha = v.color.a;
  return half4(v.color.r * alpha, v.color.g * alpha, v.color.b * alpha, v.color.a);
}

异常示例截图

像素渲染异常示例截图

内容的提问来源于stack exchange,提问作者Son Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 19:17:23