Align camera to view precisely and automatically, without manual fiddling I know there is a ton of questions and answers about this topic, but none answers my question sufficiently.

Let's say I have a viewport view that I want to render in Cycles. Pressing ALT CTRL Numpad 0 aligns the camera to this view, but it does not solve the whole problem. The thing is, I want PRECISELY this view on the render, preferably in one click, without manually moving the camera back-and-forth, changing sensor sizes etc. fiddling that will remove the unwanted border that appears and blocks the viewport partially. This whole activity wastes a lot of precious time especially if you do this 10 times a day.

What this dream action should do:


match the render resolution (proportions) to the resolution of the current view (can the resolution of current view be read by a Python script?)
make the entire view the camera view, without any borders, passe-partout etc. by automatically maneuvering sensor sizes etc. whatever is necessary to make it exactly the same view, the same camera lens angle.


Is it possible to write such a script that would do it all in one click?
I created this script based on operator simple template. 

import bpy

def main(context):
    if context.area.type == 'VIEW_3D':

        #set render resolution and lens data
        region=False;
        for reg in context.area.regions:
            if(reg.type=='WINDOW'): region=reg;

        if(region):
            context.scene.render.resolution_x=region.width
            context.scene.render.resolution_y=region.height
            context.scene.camera.data.lens=context.space_data.lens

        #set camera position
        context.scene.camera.matrix_world=context.space_data.region_3d.view_matrix
        context.scene.camera.matrix_world.invert()

        #I don't know why sensor width must be 64, but it works:
        context.scene.camera.data.sensor_width=64

        #set view from camera
        context.space_data.region_3d.view_perspective = 'CAMERA'


class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.set_render_size"
    bl_label = "set render size"


    def execute(self, context):
        main(context)
        return {'FINISHED'}


def register():
    bpy.utils.register_class(SimpleOperator)


def unregister():
    bpy.utils.unregister_class(SimpleOperator)


if __name__ == "__main__":
    register()


You can launch this script, then use set render size (you can set outer name if you want) operator.



Or you can add additional information to create an addon from this.